Home > Net >  Object.keys(data).map(v) not giving the actual key value
Object.keys(data).map(v) not giving the actual key value

Time:08-16

I want to convert an object into an array of object but my code give the wrong result like shown below..

// object
data = { user_id : '123' }

// expected result
data = [ { user_id : '123' } ]

// what I get instead
data = [ { v : '123' } ]

my code:

let arr = [];
Object.keys(data).map(v => {
  console.log(v, data[v]); // here it shows 'user_id' and '123' as it's supposed to
  arr.push({ v:data[v] }); // but here it uses the 'v' as property instead of 'user_id'
});

CodePudding user response:

You need to put v inside a square bracket

const data = {
  user_id: '123'
}

let arr = [];
Object.keys(data).map(v => {
  arr.push({
    [v]: data[v]
  });
});

console.log(arr)

Alternatively you can also use Object.entries. You dont need initialize let arr = []; as map will create a new array

const data = {
  user_id: '123'
}
const arr = Object.entries(data).map(v => {
  return {
    [v[0]]: v[1]
  }
});

console.log(arr)

CodePudding user response:

you can add element by arr[key] = value

let arr = [];
Object.keys(data).map(v => {
  console.log(v, data[v]); // here it shows 'user_id' and '123' as it's supposed to
  arr[v] = data[v]; // change here
});

CodePudding user response:

when you need to use variable as key in object, you must use [].

Example:

const key = 'user_id'
const obj = {
    [key]: 'user'
}

## result
{
'user_id': 'user
}

So change v to [v].

let arr = [];
Object.keys(data).map(v => {
  arr.push({ [v]:data[v] }); // replace v to [v] 
});
  • Related