I have an object that looks like this:
const response = {
id1-field1: true,
id1-field2: 0,
id1-field3: 3,
id2-field1: false,
id2-field2: 1,
id2-field3: 0,
id3-field1: false,
id3-field2: 0,
id3-field3: 0,
}
And I need to make an array that looks like this:
const formatted = [
{id: "id1", field1: true, field2: 0, field3: 3},
{id: "id2", field1: false, field2: 1, field3: 0},
{id: "id3", field1: false, field2: 0, field3: 0},
]
What's the best way to achieve this? This is where I'm at so far:
- Get the object's keys in an array
- Split the object keys by the hyphen
- Use the original keys to add in the object values
const response = {
"id1-field1": true,
"id1-field2": 0,
"id1-field3": 3,
"id2-field1": false,
"id2-field2": 1,
"id2-field3": 0,
"id3-field1": false,
"id3-field2": 0,
"id3-field3": 0,
}
const keys = Object.keys(response)
const split = keys.map(x => {
return ({"oldId": x, "id": x.split('-')[0], "key": x.split('-')[1]})
})
const splitWithValues = split.map( x => {
let o = x;
o.value = response[x.oldId]
return o
})
console.log(splitWithValues)