0

Sample Data

const data = [{ id: 1,iitems: [{ id: 1, name: 'R1'}]},{id: 2, items: [{ id: 1, name: 'R2'},{ id: 1, name: 'R3'}]}];

 data.map((item) => item.items).data.reduce((acc, curr) => acc.concat(curr), [])
 
 console.log(data)

What I'm trying to do here is to merge the nested to one array. but the output is like this.

data = [
{ id: 1, name: 'R1'},
{ id: 1, name: 'R2'},
{ id: 1, name: 'R3'}]

Expected output:

 data = [
    { id: 1 },
    { id: 1, name: 'R1' },
    { id: 2 },
    { id: 1, name: 'R2'},
    {id: 1, name: 'R3'}
 ];
3
  • 3
    Why is { "id": 1, "name": "R2"} not in your expected output? Commented Dec 19, 2022 at 8:27
  • Doesn't it make sense to have an array of items if you want an array and an array of objects you want references to the original ids? Commented Dec 19, 2022 at 8:28
  • 1
    @NickParsons already updated. Commented Dec 19, 2022 at 8:30

4 Answers 4

2

You can "flatten" your structure like this:

let flatten = obj => [obj, ...(obj.items || []).flatMap(flatten)]

let result = data.flatMap(flatten)

Note that this performs "deep" flattening, that is, works with sub-objects containing deeper items arrays.

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

Comments

1

You can use .flatMap() where you destructure items and the rest of the object properties into their own object (r). Then you can return an array from the .flatMap() to merge all items together into the one resulting array:

const data = [{ id: 1,items: [{ id: 1, name: 'R1'}]},{id: 2, items: [{ id: 1, name: 'R2'},{ id: 1, name: 'R3'}]}];

const res = data.flatMap(({items, ...r}) => [r, ...items]);
console.log(res);

Comments

0

use this:

const newData = data.map(item => [{id: item.id}, ...item.items]).flat(1)

1 Comment

can i ask why do you need to do this?
0

Be carefull, you have iitems and items, name error, but here is an aproach:

var data = [{ id: 1,items: [{ id: 1, name: 'R1'}]},{id: 2, items: [{ id: 1, name: 'R2'},{ id: 1, name: 'R3'}]}];

var dataNew = [];

data.forEach(element => {
  dataNew.push({
        id: element.id
      })
  if(element.items.length>0){
    element.items.forEach(elementInner => {
      
        dataNew.push({
        id: element.id,
        name:elementInner.name
      })
    })
  }
})

console.log(dataNew)

Output:

0: Object { id: 1 }
​
1: Object { id: 1, name: "R1" }
​
2: Object { id: 2 }
​
3: Object { id: 2, name: "R2" }
​
4: Object { id: 2, name: "R3" }
​
length: 5

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.