【问题标题】:Javascript move objects in a nested arrayJavascript 在嵌套数组中移动对象
【发布时间】:2021-03-31 08:22:31
【问题描述】:

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

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的元素并放入将其放入具有status === status2elements 数组中,将总count 设置为elements 数组的长度。

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

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


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

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

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

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

【问题讨论】:

  • 至少,你可以添加你的尝试......
  • 显示您已尝试自己解决此问题的代码在哪里,我们可以对其进行改进?另外,当您说 vanilla JS 时,您认为哪个版本的 ECMAS 脚本是 vanilla?
  • 我已经编辑了我的答案,但由于我不确定如何解决它,而且我也相信我的 filter().filter() 可以大大改进,我不想包括它.

标签: javascript arrays


【解决方案1】:

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

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; }

【讨论】:

  • 谢谢,这正是我所要求的。它还编辑原始数组,我的用例无法修改原始数组,但我相信我可以找到解决方案:) 谢谢!
猜你喜欢
  • 2022-01-04
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2020-07-11
  • 2021-12-06
  • 2020-12-07
  • 2021-05-27
相关资源
最近更新 更多