rod james
rod james

Reputation: 439

How to rename key inside a nested array?

Good day SO. I have seen other SO questions on how to rename a key in an array but not on a nested array.

With this array = [{id: 1, data: "Data1"}, {id: 2, data: "Data2"}] array as an example, I can change the name data to text with this code snippet:

array = array_list.map(
    ({ id, data,  }) => ({
      id: id,
      text: data,
    })
  );

However, I dont know how to rename my key in a nested array like this:

array = ([
  {
    "id": 1,
    "text": "Data1",
    "children": [{ "minor_id": 1, "minor_data": "minor data 1" }, 
        { "minor_id": 2, "minor_data": "minor data 2" }]
  }
])

I want to rename minor_id to id and minor_data to text so that I can use this for a select2 Please help.

Basically, this is my desired output:

SO Select2 Sample

Upvotes: 0

Views: 152

Answers (3)

charlietfl
charlietfl

Reputation: 171669

Use a nested map() for the children

const arr = ([
  {
    "id": 1,
    "text": "Data1",
    "children": [{ "minor_id": 1, "minor_data": "minor data 1" }, 
        { "minor_id": 2, "minor_data": "minor data 2" }]
  }
])

const res = arr.map(({children, ...other}) => {
    children = children.map(({minor_id:id , minor_data:text}) => ({id, text}))
    return {...other, children };
})

console.log(res)

Upvotes: 1

Anuj Gajbhiye
Anuj Gajbhiye

Reputation: 74

This is your given array

let array = ([
    {
      "id": 1,
      "text": "Data1",
      "children": [{ "minor_id": 1, "minor_data": "minor data 1" }, 
          { "minor_id": 2, "minor_data": "minor data 2" }]
    }
  ]);

you can parse it in this way

for (let i = 0; i < array.length; i++) {
    array[i].children.map(({minor_id, minor_data}) =>  ({id: minor_id, text: minor_data}));
      
  }

Upvotes: -1

Diwakar Singh
Diwakar Singh

Reputation: 694

Please find the required method below:-

function modify(array) {
    return array.map((item) => {
        const { children } = item
        if (children.length) {
            return {
                ...item,
                children: children.map(({ minor_id, minor_data }) => ({
                    id: minor_id,
                    text: minor_data
                }))
            }
        }
        return { ...item }
    })
}

Upvotes: 1

Related Questions