1

Many questions similar to this one like here and here, but both are hard for me to modify to my needs as the code in the answers is super concise.

I have an array with objects that looks like this:

[
    {
        id: 1,
        someProp: "value of some prop",
        metaData: {
            metaId: 123
            uuid: "2348_4354_dfgg_r343"
        }
    },
    {
        id: 2,
        someProp: "value of some prop again",
        metaData: {
            metaId: 321
            uuid: "9897_3543_ergl_j435"
        }
    }
]

I need this to look like:

[
    {
        id: 1,
        someProp: "value of some prop",
        metaId: 123
        uuid: "2348_4354_dfgg_r343"
    },
    {
        id: 2,
        someProp: "value of some prop again",
        metaId: 321
        uuid: "9897_3543_ergl_j435"
    }
]

So the properties of the nested metaData object have to become part of the parent object in each item in the array. So far I've tried:

console.log(Object.assign(
    {}, 
    ...function _flatten(o) { 
        return [].concat(...Object.keys(o)
            .map(k => 
                typeof o[k] === 'object' ?
                    _flatten(o[k]) : 
                    ({[k]: o[k]})
            )
        );
    }(events)
));

However, this only gives me on flattened object, but my array has two at the moment.

1 Answer 1

1

You could spread the nested obejct.

const
    data = [{ id: 1, someProp: "value of some prop", metaData: { metaId: 123, uuid: "2348_4354_dfgg_r343" } }, { id: 2, someProp: "value of some prop again", metaData: { metaId: 321, uuid: "9897_3543_ergl_j435" } }],
    result = data.map(({ metaData, ...o }) => ({ ...o, ...metaData }));        

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.