简体   繁体   中英

append array by index in nested array of object

I created a sample code to demo my problem, the actual data is much bigger

 const arr = [{ id: 1 }, { id: 2, items: [{ id: 1 }] }] const target = 2 const nextIndex = 1 newArr = arr.map(o => o.id === target? ({...o, items: [...o.items, { id: 'new id' }] }): o); console.log(newArr);

How to insert {id: 'new id'} by index? Above code is appending onto items array. Assuming I have a click event, user can insert the position of {id: 'new id} by index, I can't use append as it doesn't replace existing object.

expected output

[{
  id: 1
}, {
  id: 2,
  items: [{
    id: 1
  },{
   id: 'something'
}]

Above code doesn't work, adding new item to items array without using index.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements

const target = 2;
int index = arr.findIndex(v => v.id == target);
if (index > -1) {
  arr.splice(index, 1, {id: 'new id'}); // replace 1 with 0 if you just want to insert.
}

Try to pass index from onClick event

functionName = (i) => { //where i is index from onclick event

 arr.map( o, index) => {

  if(i === index)

  {
    const obj = {      //object
     id: 'new id'
    }
    arr[i].push(obj)   // push object at given index from onClick
  }

 }

}

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