繁体   English   中英

Javascript 在嵌套数组中移动对象

[英]Javascript move objects in a nested array

我有一个这样定义的数组:

const arr = [
  {
    status: 'status1',
    count: 2,
    elements: [
      {
        id: '1',
      },
      {
        id: '2',
      },
    ],
  },
  {
    status: 'status2',
    count: 1,
    elements: [
      {
        id: '3',
      },
    ],
  },
  {
    status: 'status3',
    count: 1,
    elements: [
      {
        id: '4',
      },
    ],
  },
];

该数组是动态的,但我知道元素内的status字段和id 我想要实现的是一个新数组,它包含所有相同的项目,但看起来像这样:

const arr = [
  {
    status: 'status1',
    count: 1,
    elements: [
      {
        id: '1',
      },
    ],
  },
  {
    status: 'status2',
    count: 2,
    elements: [
      {
        id: '2',
      },
      {
        id: '3',
      },
    ],
  },
  {
    status: 'status3',
    count: 1,
    elements: [
      {
        id: '4',
      },
    ],
  },
];

换句话说,如果status === status1 ,删除id === 2的元素,将count设置为elements数组的长度(或减少1 ),取出id === 2的元素并将其放入elements具有status === status2的数组,将总计count设置为elements数组的长度。

我并不擅长遍历嵌套元素并以这些方式操作数组,但使用array.filter / map等更简单的概念似乎还可以,但我无法理解所有这些。 :P

如果可能的话,我更喜欢使用香草 JS。 但如果lodash让事情变得更容易,我确实可以使用它。


编辑:当我的意思是 vanilla JS 时,我指的是不使用大量外部库,但 ES6 是我在这个项目中使用的。

我的尝试包括简单地尝试在status上过滤arr ,然后在我的id上再次过滤。 然后我知道我要移动什么项目。 但它停在那里,我也相信它可以更有效率:

const itemToMove = arr.filter(e => e.status === "status1")[0].elements.filter(e => e.id ==='2' )

我不确定在此之后如何最好地进行,因此寻求帮助。

您可以找到源对象和目标对象并拼接元素。

 const move = (data, from, to, id) => { const find = value => ({ status }) => status === value, source = data.find(find(from)), target = data.find(find(to)), index = source.elements.findIndex(o => o.id === id); if (index === -1) return; target.elements.push(...source.elements.splice(index, 1)); source.count--; target.count++; }, array = [{ status: 'status1', count: 2, elements: [{ id: '1' }, { id: '2' }] }, { status: 'status2', count: 1, elements: [{ id: '3' }] }, { status: 'status3', count: 1, elements: [{ id: '4' }] }]; move(array, 'status1', 'status2', '2'); console.log(array);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暂无
暂无

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

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