如何在过滤掉javascript后添加对象值
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
var obj = {
id: 3,
online: true
}
const result = arr.filter((item) => {
if (item.id === obj.id) {
return {
item,
online: obj.online
}
}
})
console.log(result)
应该是
{
id: 3,
username: "ted",
online: true
}
设置item.online
内部过滤方法。
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
var obj = {
id: 3,
online: true
}
const result = arr.filter((item) => {
if (item.id === obj.id) {
item.online = obj.online;
return true;
}
})
console.log(result)
OP期望的输出是单个对象。filter()
返回一个数组。find()
查找满足谓词函数返回的条件的第一个对象。让谓词函数产生副作用是很糟糕的风格。
find()
对象,然后修改它。
const arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
var obj = {
id: 93,
online: true
}
const result = arr.find(item => item.id === obj.id)
result ? result.online = true : null
console.log(result)
根据这个问题,Object.assign()
更适合解决这个问题。一个接一个的赋值创建了许多样板,需要更多的努力。
-
Object.assign()
方法从一个或多个源对象复制所有可枚举的自身属性到目标对象。它返回目标对象。 -
如果目标对象中的属性具有相同的键,则目标对象中的属性将被源中的属性覆盖。
代码块:
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
var obj = {
id: 3,
online: true
}
function mergeObjByID(item) {
if (item.id === obj.id){
//overwrite item value
Object.assign(item,obj)
return true
}
}
const result = arr.filter(mergeObjByID);
console.log(result)
关于Object.assign()的更多信息示例:
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }