如何在JavaScript对象数组(Lodash)中设置所有对象的特定属性值



我有以下对象数组:

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

如何设置每个对象的"状态"属性为" Active" 。因此,由此产生的数组将是:

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

此外,如果不存在,则应创建"活动"属性。

我可以使用循环来做到这一点。但是我非常确定Lodash可以在一行中这样做:

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

you 需要lodash


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


显示三种方法


不变版本(我们使用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);

的确,您不需要 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' );

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

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

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

最新更新