简体   繁体   English

如何检查一个对象数组是否包含另一个对象数组的所有 id JS

[英]How to check if an array of objects contains all the ids of another array of objects JS

I have 2 arrays of Objects;我有 2 个对象数组;

// First one :
[0: {id: 1},
1: {id: 2},
2: {id: 3},
3: {id: 4}]

// Second one :
[0: {id: 10},
1: {id: 1},
2: {id: 4},
3: {id: 76},
4: {id: 2},
5: {id: 47},
6: {id: 3}]

I'd like to test if the second one has at least every same IDs of the first one.我想测试第二个是否至少具有与第一个相同的 ID。 Which would be true in this case because the second one contains 1, 2, 3 and 4 IDs.在这种情况下这是正确的,因为第二个包含 1、2、3 和 4 个 ID。

I tried to use some() and every() but it doesn't work properly我尝试使用 some() 和 every() 但它不能正常工作

My try :我的尝试:

let res = this.trainingEpisodesList.some( episode => {
    this.completedEpisodes.every( userEpisode => {
         userEpisode.id == episode.id;
     })
});

Thanks ;)谢谢 ;)

ES7, ES7,

let result = one.map(a => a.id);
let result2 = two.map(a => a.id);
const final_result = result.every(val => result2.includes(val));

ES5, ES5,

var result = one.map(a => a.id);
var result2 = two.map(a => a.id);

var final_result = result.every(function(val) {

  return result2.indexOf(val) >= 0;

});

You can do this using every and find :你可以使用everyfind来做到这一点:

 let completedEpisodes = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ] let trainingEpisodesList = [ {id: 10}, {id: 1}, {id: 4}, {id: 76}, {id: 2}, {id: 47}, {id: 3} ] let containsAllCompleted = trainingEpisodesList.every(c => completedEpisodes.find(e=>e.id==c.id)); console.log(containsAllCompleted);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM