简体   繁体   English

如何在嵌套数组对象中删除和添加项目

[英]How to delete and add item in nested array object

I have nested array objects which have items in it.我有嵌套的数组对象,其中包含项目。 I want to remove item from id:4 except first item and add it id:5 object.我想从id:4删除除第一项之外的项目并将其添加到id:5对象。

const data = [
  {
    id: 1,
    items: [ { id:11 }, {id:12 } ],
  },
  {
    id: 2,
    items: [ { id:21 } ],
  },
  {
    id: 3,
    items: [ { id:31 } ],
  },
  {
    id: 4,
    items: [ { id:41 }, {id:42 } ],
  },
  {
    id: 5,
    items: [ { id:51 } ],
  },
]

so my resultant array should be like this所以我的结果数组应该是这样的

 const data = [
  {
    id: 1,
    items: [ { id:11 }, {id:12 } ],
  },
  {
    id: 2,
    items: [ { id:21 } ],
  },
  {
    id: 3,
    items: [ { id:31 } ],
  },
  {
    id: 4,
    items: [ { id:41 } ],
  },
  {
    id: 5,
    items: [ {id:42 }, { id:51 } ],
  },
]

I'll do it in two steps, first to get all of the items in the item with id 4 except the first one:我将分两步完成,首先获取 id 为 4 的项目中除第一个之外的所有项目:

let moreItems = [];

data.forEach((item) => {
    if (item.id === 4) {
       
       while(item.items.length > 1) {
        moreItems.push(item.items[item.items.length-1]);
        item.items.pop();
       }
    }
});

moreItems will be the array to add to the items in the item with id 5. moreItems 将是要添加到 id 为 5 的项目中的项目的数组。


data.forEach((item) => {
    if (item.id === 5) {
        if (moreItems.length > 0) {
            item.items = item.items.concat(moreItems);
        }
    }
});

Maybe something like this?也许是这样的?

let v = data[3].items.pop()
data[4].items.push(v)

The question was not the most clear.这个问题不是最清楚的。 If you need to do this based on some condition or logic you will have to do that yourself.如果您需要根据某些条件或逻辑执行此操作,则必须自己执行此操作。

如果您需要从 id=4 复制所有项目,请使用以下代码: data[4].items.push(data[3].items.splice(1,data[3].items.length));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM