我有以下对象数组:
var arr = [
{
id : "a1",
guid : "sdfsfd",
...
value : "abc",
status: "active"
},
{
id : "a2",
guid : "sdfsfd",
...
value : "def",
status: "inactive"
},
{
id : "a2",
guid : "sdfsfd",
...
value : "def"
},
...
]
Run Code Online (Sandbox Code Playgroud)
如何将每个对象的"status"属性设置为"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"
},
...
]
Run Code Online (Sandbox Code Playgroud)
此外,如果不存在,这应该创建属性"活动".
我可以使用for循环来做到这一点.但我非常确定lodash可以在一行中完成这样的操作:
arr = _.set_property(arr, "status", "active");
Run Code Online (Sandbox Code Playgroud)
事实上,你不需要 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');
});
Run Code Online (Sandbox Code Playgroud)
如果你想把它抽象化,你可以构建一个Lodash mixin:
_.mixin({
setProperty: function(arr, key, val) {
_.forEach(arr, function (obj) {
_.set(obj, path, val);
});
}
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以完全按照您的描述使用它:
_.setProperty( arr, 'status', 'active' );
Run Code Online (Sandbox Code Playgroud)
您不需要为此。
第一个对象缺少您的status属性,它将被添加。
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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16658 次 |
| 最近记录: |