Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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'
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading