首页 > 解决方案 > 如何在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
}

标签: javascript

解决方案


设置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)


推荐阅读