javascript - 如何使用 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 找到元素,将它从数组中删除,然后将新对象推送到数组中,但它当然总是在列表的末尾,这不适合我。
任何帮助将非常感激。
解决方案
您可以使用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);
推荐阅读
- java - 在Java中实现最近邻算法(使用动态编程)
- python - 当我的枪旋转时,我怎样才能让我的 Rect 跟随我的枪尖?游戏
- python - 熊猫根据特定列计算百分比变化
- ios - 使用 UIDocument 和 Swift 将 plist NSdata 与 iCloud 同步
- r - R:找到在一定次数的迭代中不减少的向量中的位置
- javascript - 通过 CDN 提供 JS 小部件
- python-3.x - 如何流式传输包含文件结构中其他压缩对象的 tar 目录/文件夹?
- javascript - 如何在调用对象后更改它以便可以将其插入到链接中
- mysql - 需要编写一个查询而不是 5 个查询来获得所有 5 个状态的结果
- c# - 如何在 C# 中对证书签名请求进行自签名?充气城堡还可以