【问题标题】:How to set specific property value of all objects in a javascript object array (lodash)如何在 javascript 对象数组(lodash)中设置所有对象的特定属性值
【发布时间】:2017-07-06 07:14:22
【问题描述】:

我有以下对象数组:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "abc",
    status: "active"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: "inactive"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def"
  },
  ...
]

如何将每个对象的“状态”属性设置为“活动”。所以结果数组将是:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "abc",
    status: "active"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: "active"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: "active"
  },
  ...
]

此外,如果不存在,这应该创建属性“活动”。

我可以使用 for 循环来做到这一点。但我很确定lodash 可以在一行中做到这一点:

arr = _.set_property(arr, "status", "active");

【问题讨论】:

标签: javascript lodash


【解决方案1】:

不需要为此需要lodash


第一个对象缺少您的状态属性,它将被添加。


展示三种方法


IMMUTABLE VERSION(我们使用map 创建一个新数组)

const arrImmutableVersion = arr.map(e => ({...e, status: "active"}));

可变版本(我们更改原始数组)

arr.forEach((el)=>{el.status = "active";}) 

arr.forEach(function(el){el.status = "active";}) 

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",   
    value : "abc"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",   
    value : "def",
    status: "inactive"
  },
  {
    id    : "a2",
    guid  : "sdfsfd",   
    value : "def",
    status: "active"
  } 
];

// SHOWING THREE WAYS HOW YOU CAN DO IT

// MUTABLE VERSIONS - We change the original array
arr.forEach((el)=>{el.status = "active";}) // ES6
// or
arr.forEach(function(el){el.status = "active";}) 
//or
// IMMUTABLE VERSION - We create a new array using `map`
const arrImmutableVersion = arr.map(e => ({...e, status: "active"})); // ES6
//--------------------------------------------------------------


// RESULTS:
console.log("logging results of object 'arr'");
console.log(arr);
console.log("---------------------------------------------------------");
console.log("logging results of object 'arrImmutableVersion'");
console.log(arrImmutableVersion);

【讨论】:

  • 不可变 ES6/ES2015 版本:const newArr = arr.map(e => ({...e, status: "active"}))
【解决方案2】:

确实,您不需要Lodash,但问题被标记为 Lodash,并且使用 Lodash 提供了一些有用的防御措施,可以降低出错的风险。该解决方案使用_.forEach_.set

 // _.forEach won't throw errors if arr is not an array...
 _.forEach(arr, function (obj) {
    // _.set won't throw errors if obj is not an object. With more complex objects, if a portion of the path doesn't exist, _.set creates it
     _.set(obj, 'status', 'active');
 });

如果你想让它抽象,你可以构建一个 Lodash mixin:

_.mixin({
    setProperty: function(arr, key, val) {
        _.forEach(arr, function (obj) {
            _.set(obj, path, val);
        });
    }
});

然后,您可以完全按照您的描述使用它:

_.setProperty( arr, 'status', 'active' );

【讨论】:

  • 不错的“混合”示例!另一种可能性,虽然有点“加载”单行:_.map(arr, function(o) { _.set(o, 'status', 'active'); });
  • 另一条线:_.each(arr, itm => _.set(itm, 'status', 'active'));
  • 你不需要 lodash 来做这样简单的事情。
【解决方案3】:

一种更简单、更清洁的方式!

如果你想以适当的方式使用 func 编程

  myArray = myArray.map(arrayElem => {
    arrayElem.property = newValue
    return arrayElem
  })

【讨论】:

  • ESLint:赋值给函数参数“i”的属性。(no-param-reassign)
猜你喜欢
  • 2021-07-19
  • 2015-07-17
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 2013-06-11
  • 2016-07-26
  • 2017-08-23
相关资源
最近更新 更多