如何在javascript对象数组中设置所有对象的特定属性值(虚线) [英] How to set specific property value of all objects in a javascript object array (lodash)

查看:745
本文介绍了如何在javascript对象数组中设置所有对象的特定属性值(虚线)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象数组:

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

如何将每个对象的状态"属性设置为活动" .因此,结果数组将为:

How to set "status" property of each object to "active". So the resulting array will be:

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

此外,如果不存在,这应该创建属性"active".

Additionally this should create the property "active" if doesn't exists.

我可以使用for循环来做到这一点.但我非常确定 lodash 可以在一行中做到这一点,例如:

I can do this using for loops. But I'm pretty much sure lodash can do this in one line like:

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

推荐答案

实际上,您不需要 _.forEach

Indeed, you don't need Lodash, but the question is tagged Lodash, and using Lodash offers some useful defenses that reduces the risk of errors. This solution utilizes _.forEach and _.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:

If you wanted to make it abstract, you could build a Lodash mixin:

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

然后,您可以按照说明完全使用它:

Then, you could use it exactly as you described:

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

这篇关于如何在javascript对象数组中设置所有对象的特定属性值(虚线)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆