如何设置javascript对象数组中所有对象的特定属性值(lodash)

时间:2017-02-16 23:08:19

标签: javascript lodash

我有以下对象数组:

rd-test

如何设置"状态"每个对象的属性为"活跃" 。因此得到的数组将是:

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

此外,这应该创建属性"活跃"如果不存在。

我可以使用for循环来做到这一点。但我非常确定lodash可以在一行中执行此操作,如:

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"
  },
  ...
]

3 个答案:

答案 0 :(得分:7)

事实上,你并不需要 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' );

答案 1 :(得分:5)

你不需要lodash

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



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);




答案 2 :(得分:1)

更简单,更清洁的方式!!!!!

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

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