首页 > 解决方案 > 扩展对象并有条件地修改一个属性 ES6

问题描述

我有如下对象

const myObject = {
      "Obj1" :[ {
         name:"test",
         down:"No"
         Up: "Yes",
        },
        { }, {}....
           
       ],
     "Obj2" :[ {}, {}......

           
       ],
     "Obj3" : [ {}, {}, {....
           
       ],
}

我想克隆上面的对象并想修改“Obj1”如果name =“test”然后将其设置为“是”

基本上我想有条件地传播对象属性。

标签: javascriptecmascript-6

解决方案


好吧,这个问题有点不清楚。无论如何,如果您想从克隆对象有条件地更新 '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)
)



推荐阅读