过滤两个对象数组

时间:2017-05-04 12:11:48

标签: javascript

我必须使用对象数组 arr1 = [....] arr2 = [....]

现在我想根据它的id找到匹配的对象,然后将值从一个复制到另一个我使用for循环创建它:

for (let newCampaignState of data) {
            for (let oldCampaignState of this.campaigns) {
                if (oldCampaignState.id === newCampaignState.id) {
                    oldCampaignState.name = newCampaignState.name;
                }
            }
        }

我怎么能用更多功能编程来做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用滤镜功能:

<强>代码

&#13;
&#13;
var arr1 = [{
  name: 'category1',
  id: '1'
}, {
  name: 'category3',
  id: '2'
}, {
  name: 'category2',
  id: '2'
}];

var arr2 = [{
  name: 'category2',
  id: '5'
}, {
  name: 'category2',
  id: '1'
}, {
  name: 'category2',
  id: '2'
}];


let filtered = [];

arr1.filter(function(newData) {
  return arr2.filter(function(oldData) {
      if (newData.id === oldData.id && newData.name === oldData.name) {
      filtered.push({
        'id': newData.id,
        'name': newData.name
      })
    }
  })
});

document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(JSON.stringify(filtered, null, 4)));
&#13;
body {
  white-space: pre;
  font-family: monospace;
}
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
&#13;
&#13;
&#13;