首页 > 解决方案 > 如何使用 ramda 表达式编辑数组内的对象?

问题描述

我有一个这样的数组:

[
  {
    id: '1852',
    label: 'One',
    types: [1, 2, 4]
  },
  {
    id: '1854852',
    label: 'Two',
    types: [1, 2]
  },
  {
    id: '4581852',
    label: 'Three',
    types: [1]
  }
]

id 属性是唯一的,我用它来获取对象。

我对一个对象(例如第三个)进行了更改,我希望它是这样的:

  {
    id: '4581852',
    label: 'new Three',
    types: [1, 7, 9]
  }

如何对阵列进行适当的更改?

因为现在我正在做一个不好的解决方案,我试图通过它的 id 找到元素,将它从数组中删除,然后将新对象推送到数组中,但它当然总是在列表的末尾,这不适合我。

任何帮助将非常感激。

标签: javascriptarraysobjectupdatesramda.js

解决方案


您可以使用Array#find来获取对象,然后直接更新其属性。

const arr = [
  {
    id: '1852',
    label: 'One',
    types: [1, 2, 4]
  },
  {
    id: '1854852',
    label: 'Two',
    types: [1, 2]
  },
  {
    id: '4581852',
    label: 'Three',
    types: [1]
  }
]
const obj = arr.find(({id})=>id==='4581852');
obj.label = 'new Three';
obj.types.push(7,9);
console.log(arr);


推荐阅读