'Unpack array of objects to another object [closed]
I have next array:
const myData = [
{
“VAR_1”: “bla-bla”
},
{
“VAR_2”: “test”
},
{
“VAR_3”: “oop”
},
…..
];
I need to unpack it like this:
const {
VAR_1,
VAR_2,
VAR_3,
} = myData;
Solution 1:[1]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
const myData = [
{
"VAR_1": "bla-bla"
},
{
"VAR_2": "test"
},
{
"VAR_3": "oop"
}
];
const {VAR_1, VAR_2, VAR_3} = Object.assign({}, ...myData)
console.log(VAR_1, VAR_2, VAR_3)
Solution 2:[2]
I think the OP means to reduce the input arrays, combining the keys of the objects therein...
const myData = [{
VAR_1: "bla - bla"
},
{
VAR_2: "test"
},
{
VAR_3: "oop"
}
];
let singleObject = myData.reduce((acc, obj) => {
acc = { ...acc, ...obj }
return acc;
}, {});
console.log(singleObject)
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 | adiga |
| Solution 2 | danh |
