I have the following data:
[
[
{
"name": "color",
"value": "red",
"id": "colorID"
},
{
"altText": "",
"uri": "someURL",
"id": "someID",
"localFile": {
"childImageSharp": {
"fluid": {
"fluidData": "someString",
"fluidData2": 1.567
}
}
}
}
]
]
I am trying to combine that into one Object in which all properties of both should be present. "localfile" can stay nested as in I don't need it flattened or anything, just for everything to be in one single object if at all possible.
I am getting the current data structure by doing something like this:
const variants = post.variations.nodes.map(function (variantItem) { return [variantItem.attributes.nodes[0], variantItem.featuredImage.node] });
I tried combining them with Object.assign() and also using the spread operator. I found a few other snippets but those only worked if both objects share the same keys.
I thought this should be quite simple but have been scratching my head over it for too long. Any input would be much appreciated.
3 Answers 3
It's as simple as
{...a[0][0], ...a[0][1]}
where a is your array of an array of objects.
This will spread both objects into one.
2 Comments
You can use Array.prototype.reduce() after flattening the outer array with Array.prototype.flat() like so:
const arr = [
[
{
"name": "color",
"value": "red",
"id": "colorID"
},
{
"altText": "",
"uri": "someURL",
"id": "someID",
"localFile": {
"childImageSharp": {
"fluid": {
"fluidData": "someString",
"fluidData2": 1.567
}
}
}
}
]
]
const obj = arr.flat().reduce((acc, curr) => {
return {
...acc,
...curr
}
}, {});
console.log(obj);
3 Comments
Use destructuring and ... operator.
const getObject = ([[first, second]]) => ({...first, ...second});
const data = [
[
{
"name": "color",
"value": "red",
"id": "colorID"
},
{
"altText": "",
"uri": "someURL",
"id": "someID",
"localFile": {
"childImageSharp": {
"fluid": {
"fluidData": "someString",
"fluidData2": 1.567
}
}
}
}
]
]
console.log(getObject(data));