javascript - 扩展对象并有条件地修改一个属性 ES6
问题描述
我有如下对象
const myObject = {
"Obj1" :[ {
name:"test",
down:"No"
Up: "Yes",
},
{ }, {}....
],
"Obj2" :[ {}, {}......
],
"Obj3" : [ {}, {}, {....
],
}
我想克隆上面的对象并想修改“Obj1”如果name =“test”然后将其设置为“是”
基本上我想有条件地传播对象属性。
解决方案
好吧,这个问题有点不清楚。无论如何,如果您想从克隆对象有条件地更新 'up' if 'name' === 'test' :
import { cloneDeep } from lodash/fp;
// you can use also JSON stringify + JSON parse
// spread operator will only shallow copy your object
//clone it
const deepClonedObject = cloneDeep(myObject);
// update items accordingly to your needs
deepClonedObject.obj1 = deepClonedObject.obj1.map(item => (item.name === 'test'
? { ...item, up: 'Yes' }
: item)
)
推荐阅读
- python - 在每组 Pandas 数据框中创建一个点列表
- laravel - Try catch 在 Laravel 中间件中无法正常工作?
- android - 如何模拟被Android系统杀死的前台服务
- html - 更改标题字体大小会使 div 不对齐
- python - Python Pygame通过共享使用调用时传递参数
- swiftui - 如何在渲染之前执行自定义更新?
- python - 我在哪里可以下载预训练的 word2vec 地图?
- python - Numpy 数组和轴
- javascript - Console.log() 有一个值,但是当我将它与 map 函数一起使用时,它变得未定义 [ReactJS]
- vb.net - 如何将一个类的公共属性设置为另一个类的实例?