简体   繁体   中英

Combine different Objects in Array

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.

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.

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);

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM