【问题标题】:Update a Single Field of Object in Object Array in Javascript/Lodash在 Javascript/Lodash 中更新对象数组中的单个对象字段
【发布时间】:2017-07-13 12:04:07
【问题描述】:

有没有办法更新对象数组中对象中的单个字段?

PeopleList= [
   {id:1, name:"Mary", active:false}, 
   {id:2, name:"John", active:false}, 
   {id:3, name:"Ben", active:true}]

例如,将 John 的 active 设置为 true。

我尝试在 Lodash 中执行此操作,但它没有返回正确的结果。它返回一个 lodash 包装器。

        updatedList = _.chain(PeopleList)
       .find({name:"John"})
       .merge({active: true});

【问题讨论】:

    标签: javascript arrays filter lodash


    【解决方案1】:

    你甚至不需要 lodash 来使用 es6:

    PeopleList.find(people => people.name === "John").active = true;
    //if the record might not exist, then
    const john = PeopleList.find(people => people.name === "John")
    if(john){
      john.active = true;
    }
    

    或者如果您不想改变原始列表

    const newList = PeopleList.map(people => {
      if(people.name === "John") {
        return {...people, active: true};
      }
      return {...people};
    });
    

    【讨论】:

    • 我认为 Lodash 更适合初学者,因此他们不必处理转译。
    【解决方案2】:

    _.find(PeopleList, { name: 'John' }).active = true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2022-11-01
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多