'Move keys of object to individual properties of child objects, creating an array [duplicate]
The API data looks like this:
{
"00041335": {
"productId": "8e786e6b",
"variantId": "0b43df16"
},
"00032183": {
"productId": "9e780e6d",
"variantId": "0b48df17"
}
}
I want to make it like this:
[
{
"skuId": "00041335",
"productId": "8e786e6b",
"variantId": "0b43df16"
},
{
"skuId": "00032183",
"productId": "9e780e6d",
"variantId": "0b48df17"
}
]
How to restructure the object? Is reduce appropriate or is there a better way?
Solution 1:[1]
There might be a better way using more efficient destructuring but this did the trick for me:
taking the first object's key value and inserting it into a new object with property id1. then take the object nested in object1 and spread it over the rest of the object.
let obj1 ={ "00041335332183": { "Id2": "8e786e6b", "Id3": "0b43df16" } }
let keyValue = Object.keys(obj1);
let newObj = {
id1: keyValue[0],
...obj1[keyValue[0]]
}
Solution 2:[2]
Easiest way would to use Object.keys()and then you can merge the two objects with the spread operator (...).
const o ={ "00041335332183": { "Id2": "8e786e6b", "Id3": "0b43df16" } }
console.log({ Id1: Object.keys(o)[0], ...Object.values(o)[0] })
Solution 3:[3]
First of all, you need to find the first key of your object, in order to do that you can use Objects
Object.keys(yourobject) provides your keys in the array format, out of these keys the first index is your ID.
Now you need to create a new object and merge the rest of the data by using the spread operator (...) Learn from here
let data = { "00041335332183": { "Id2": "8e786e6b", "Id3": "0b43df16" } }
let parsedObject = {id: Object.keys(data)[0], ...data[Object.keys(data)[0]]}
console.log (parsedObject)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tempnameenjoyer |
| Solution 2 | Maik Lowrey |
| Solution 3 |
