Avocado
Avocado

Reputation: 327

How to flatten a nested object?

I have the following nested object:

[
{
    "id": "b2dgd67e7e7",
    "fields": {
        "task1": "task 1",
        "task2": "task 2"
    }
},
 {
    "id": "b2dgd67e7e8",
    "fields": {
        "task1": "task 3",
        "task2": "task 4"
    }
}
]

I would like to flatten it to the following format bellow:...........................................

[
{

    "fields": {
        "task1": "task 1",
        "task2": "task 2",
        "id": "b2dgd67e7e7",
    }
},
 {

    "fields": {
        "task1": "task 3",
        "task2": "task 4",
        "id": "b2dgd67e7e8",
    }
}
]

Upvotes: 0

Views: 52

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50684

You could use .map() on your array to build a new array of mapped objects. To map each object, you can destructure the id and fields property from the object, and then return a new object which contains your fields property along with the original contents of the fields object value as well as the remaining outside properties (such as id):

const arr = [{ "id": "b2dgd67e7e7", "fields": { "task1": "task 1", "task2": "task 2" } }, { "id": "b2dgd67e7e8", "fields": { "task1": "task 3", "task2": "task 4" } } ];

const flattenToKey = (arr, key) => 
  arr.map(({[key]: k, ...r}) => ({[key]: {...k, ...r}}));

const res = flattenToKey(arr, 'fields');
console.log(res);

Upvotes: 2

Related Questions