1

I'm sorry if this is redundant with other posts but I currently have the following array:

let test = {1:100, 2:200, 3:300}

But I'd like to convert this to:

test = [
{id: 1, value: 100},
{id: 2, value: 200},
{id: 3, value: 300}
]

Any help appreciated - even just pointing me to posts that solve this question :)

MayaGans
  • 1,815
  • 9
  • 30
  • That definitely gets me closer, but I'd like to the objects to have the names "id" and "value" whereas that just creates array pairs - I'll try using that as a start! – MayaGans Aug 23 '20 at 00:23
  • If you’re looking for the inverse of this: [How do I convert array of Objects into one Object in JavaScript?](/q/19874555/4642212). – Sebastian Simon Sep 21 '21 at 08:00

3 Answers3

2

You can use Object.entries to get an array of key, value pairs and then map that to an array of objects:

let test = {1:100, 2:200, 3:300};

let out = Object.entries(test).map(([k, v]) => ({ id : k, value: v }));
console.log(out);
Nick
  • 138,499
  • 22
  • 57
  • 95
1

Here's a version using keys and map:

var obj = {1:100,2:200,3:300}
var result = Object.keys(obj).map((key) => ({ id: key, value: obj[key]}));

console.log(result)
Brian Lee
  • 17,904
  • 3
  • 41
  • 52
1

Using Object.entries() and some destructuring

let test = {1:100, 2:200, 3:300}
let res = Object.entries(test).map(([id, value]) => ({id, value}))
   


console.log(res)
charlietfl
  • 170,828
  • 13
  • 121
  • 150