如何设置javascript对象数组(lodash)中所有对象的特定属性值
我有以下对象数组:如何设置javascript对象数组(lodash)中所有对象的特定属性值,javascript,lodash,Javascript,Lodash,我有以下对象数组: var arr = [ { id : "a1", guid : "sdfsfd", ... value : "abc", status: "active" }, { id : "a2", guid : "sdfsfd", ... value : "def", status: "inactive" }, { id : "a2", guid
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"
},
...
]
此外,如果不存在,则应创建属性“active”
我可以使用for循环来实现这一点。但我很确定我们可以用一句话做到这一点,比如:
arr = _.set_property(arr, "status", "active");
您不需要
lodash
第一个对象缺少status属性,将添加它
展示三种方法如何做到这一点
不可变版本(我们使用
map
创建一个新数组)
可变版本(我们更改原始数组)
或
var-arr=[
{
id:“a1”,
guid:“sdfsfd”,
价值:“abc”
},
{
id:“a2”,
guid:“sdfsfd”,
值:“def”,
状态:“非活动”
},
{
id:“a2”,
guid:“sdfsfd”,
值:“def”,
状态:“活动”
}
];
//展示三种方法如何做到这一点
//可变版本-我们更改原始数组
arr.forEach((el)=>{el.status=“active”;})//ES6
//或
arr.forEach(函数(el){el.status=“active”;})
//或
//不可变版本-我们使用'map'创建一个新数组`
const arrimutableversion=arr.map(e=>({…e,状态:“活动”}));//ES6
//--------------------------------------------------------------
//结果:
log(“对象'arr'的日志记录结果”);
控制台日志(arr);
console.log(“------------------------------------------------------------------”;
log(“对象'arrimutableversion'的日志记录结果”);
console.log(不可变版本)代码>确实,您不需要,但问题是标记为Lodash,使用Lodash提供了一些有用的防御措施,可以降低出错的风险。此解决方案利用和
如果您想将其抽象化,可以构建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
})
可能重复的Hi尝试此链接它试图做同样的事情,但索引<代码>arr.forEach(it=>it.status='active')代码>使用原力。花点时间看看Array
和Object
的全球标准JavaScript对象和方法:不要使用过时库的副本,从而维护实用知识不变的ES6/ES2015版本:const newArr=arr.map(e=>({…e,status:“active”}))
Nice'mixin'示例!另一种可能,虽然有点“加载”了一行代码:.map(arr,function(o){u.set(o,'status','active');})代码>另一行:每一行(arr,itm=>u.set(itm,'status','active')代码>ESLint:分配给函数参数“i”的属性(无参数重新分配)
// _.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');
});
_.mixin({
setProperty: function(arr, key, val) {
_.forEach(arr, function (obj) {
_.set(obj, path, val);
});
}
});
_.setProperty( arr, 'status', 'active' );
myArray = myArray.map(arrayElem => {
arrayElem.property = newValue
return arrayElem
})