【问题标题】:Remove an object in array from array从数组中删除数组中的对象
【发布时间】:2021-04-21 21:05:12
【问题描述】:

我想删除 0 id 的列表中 cardItems 的 1 id 并保持列表的顺序。最好的方法是什么?

   lists: [
        {
          id: '0',
          title: 'LIST 1',
          cardItems: [
            {
              id: '0',
              text: 'Card 1',
            },
            {
              id: '1',
              text: 'Card 2',
            },
            {
              id: '2',
              text: 'Card 3',
            },
          ],
        },
    ]

【问题讨论】:

  • 请提供预期的输出。但是,这看起来像是以前被问过几次的那种问题。
  • 您的描述不清楚,请写清楚。当然,我可能认为你的问题和这个问题类似stackoverflow.com/questions/42005096/…

标签: javascript ecmascript-6


【解决方案1】:

您可以使用.find通过id获取列表项,然后使用.filter移除卡片项:

const lists = [
  {
    id: '0',
    title: 'LIST 1',
    cardItems: [
      { id: '0', text: 'Card 1' },
      { id: '1', text: 'Card 2' },
      { id: '2', text: 'Card 3' },
    ],
  },
];

const removeCardItem = (list, listItemId, cardItemId) => {
  const arr = [...list];
  // get list item by id
  const item = arr.find(listItem => listItem.id === listItemId);
  // remove card item by id if found
  if(item)
    item.cardItems = item.cardItems.filter(cardItem =>
      cardItem.id !== cardItemId
    );
  return arr;
}

console.log( removeCardItem(lists, '0', '1') );

【讨论】:

    【解决方案2】:

    类似的东西

    if(lists[0].cardItems[0].id === 1){
        lists[0].cardItems.splice(0,1);
    }
    

    显然这只会检查一个值,但这可以很容易地实现为循环或嵌套循环或您需要的任何内容。 (我不知道,因为我看不到你所有的代码)

    您的问题有点难以理解,但这是我帮助您的最佳猜测!如果这不是您要寻找的答案,请向我们提供更多信息,以便我们更有效地帮助您!

    【讨论】:

      猜你喜欢
      • 2012-05-12
      • 2015-08-29
      • 1970-01-01
      • 2020-08-14
      • 2016-11-26
      • 2016-05-19
      • 2011-04-04
      • 2013-03-16
      相关资源
      最近更新 更多