javascript - 如何在javascript中过滤后添加对象值
问题描述
过滤掉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)
推荐阅读
- c# - 如何将 ASCII 代码视为字符串而不是字符
- pine-script - 如何确定蜡烛的大小是否是看涨和看跌的两倍
- javascript - 点/括号符号 - 动态键
- ansible - 使用ansible,我如何遍历列表并将项目用作查找值的键
- r - groupby 然后在许多列中找到最大值
- javascript - 在 NodeJs 中使用 3rd 方 lib 文件并出现 LNK2001 错误
- python - 模块已安装但 PyCharm 无法识别
- point-clouds - 可视化 Velodyne 数据集
- javascript - Javascript Fetch API 无法控制即将到来的响应
- java - 如何加密mysql中特定列的数据?