简体   繁体   English

如何根据JavaScript中的值检查对象是否在数组中?

[英]How to check if objects are in an array based on a value in JavaScript?

For example, how do I check if ALL the objects in array2 exist in array1 based on their id ? 例如,如何基于id检查array1是否存在array2所有对象?

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
const array2 = [{ id: 1 }, { id: 2 }]

For some reason, I couldn't find the solution on Google. 出于某种原因,我无法在Google上找到解决方案。

I thought about this: 我想到了这个:

const result = array1.every(obj1 => {
  // what do use here? includes? contains?
})

console.log(result)

But I'm kind of stuck in the middle of the code. 但我有点陷入代码的中间。 The most logical solution to me was to use includes . 对我来说最合乎逻辑的解决方案是使用includes However, includes doesn't seem to take a function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes . 但是, includes似乎没有功能: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes So I'm not sure if I can check the objects by id. 所以我不确定我是否可以通过id检查对象。

includes will only be true if both objects are the same reference in memory, which is (probably) not the case. 如果两个对象在内存中都是相同的引用,则includes将为true,这可能(可能)不是这种情况。 Instead, I'd create a Set of array1 's id s initially, and then check to see if every array2 id is in the set. 相反,我想创建一个Setarray1id小号开始,然后检查是否每一个array2 id是在集合。 This way, you only have to iterate over array1 once, at the very beginning ( Set s have O(1) lookup time): 这样,您只需要在一开始就迭代一次array1Set s有O(1)查找时间):

 const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 1 }, { id: 2 }]; const idSet = new Set(array1.map(({ id }) => id)); console.log( array2.every(({ id }) => idSet.has(id)) ); 

(Arrays do not have a contains function) (数组没有contains函数)

var matching = [];

for (var j = 0; j < array1.length; j++) {
    for (var i = 0; i < array2.length; i++) {
        if (array2[i].id === array1[j].id) {
            matching.push(array2[i].id);       
        }
    }
}

if (array2.length === matching.length) {
    console.log("All elements exist");
} else {
    console.log("One or more of the elements does not exist");
}

Like this, using Array.prototype.every in combination with Array.prototype.some() : 像这样,将Array.prototype.everyArray.prototype.some()结合使用:

const result = array2.every(o2 => array1.some(o1 => o1.id === o2.id));

This will check if every element in array2 has a matching element in array1 . 这将检查array2中的每个元素是否在array1都有匹配的元素。


Here's a complete snippet: 这是一个完整的片段:

 const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 1 }, { id: 2 }]; const result = array2.every(o2 => array1.some(o1 => o1.id === o2.id)); console.log(result); 

If array1 is large, or used repeatedly to perform this operation, the Set -based approach proposed in other answers is more optimized. 如果array1很大,或者重复使用它来执行此操作,则在其他答案中提出的基于Set的方法更加优化。

Similar type of question is already asked. 已经提出了类似的问题。 You can refer that also on this link Check if every element in one array is in a second array 您也可以在此链接上引用它检查一个数组中的每个元素是否都在第二个数组中

 const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array2 = [{ id: 1 }, { id: 2 }]; let array1ids = array1.map(a => a.id); const result = array2.every(a => array1ids.includes(a.id)); console.log(result); const array3 = [{ id: 1 }, { id: 2 }, { id: 3 }]; const array4 = [{ id: 1 }, { id: 6 }]; let array3ids = array3.map(a => a.id); const result2 = array4.every(a => array3ids.includes(a.id)); console.log(result2); 

For large arrays, I recommend pre-processing the array that's used as the criteria to create a Set so that each check is an O(1) lookup and overall O(n) instead of O(n^2). 对于大型数组,我建议预处理用作创建Set的条件的数组,以便每次检查是O(1)查找和整体O(n)而不是O(n ^ 2)。 This code makes a couple assumptions though, namely: 这段代码做了几个假设,即:

  • The criteria is based on a select() function of the object , its index in the array, and a reference to the array . 标准是基于一个select()的功能object ,其index阵列中,并以一个参考array
  • The selection used as the criteria returns a primitive and can perform an equality check identical to a Set using a === b || (a !== a && b !== b) 用作条件的选择返回基元,并且可以使用a === b || (a !== a && b !== b)执行与Set相同的相等性检查 a === b || (a !== a && b !== b) (to deal with a and b being NaN ) a === b || (a !== a && b !== b) (处理abNaN

 const has = select => array => { const set = new Set(array.map(select)) return (object, index, array) => set.has(select(object, index, array)) } const hasId = has(({ id }) => id) const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }] const array2 = [{ id: 1 }, { id: 2 }] const result1 = array1.every(hasId(array2)) const result2 = array2.every(hasId(array1)) console.log(result1) console.log(result2) 

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

相关问题 如何检查值是否在具有基于另一个数组的对象的数组中 - How to check if value is in an array with objects based on another array 如何根据 ID 检查对象数组并在 JavaScript 中添加新属性 - How to check array of objects based on ID and add new property in JavaScript Javascript-根据对象值对带有对象的数组进行排序 - Javascript - Sorting array with objects based on objects value 如何检查具有多个对象的数组中的值是否存在-JavaScript? - How can I check if a value exists in an array with multiple objects - javascript? 如何检查 Javascript 对象数组是否始终具有相同的值 - How to check if Javascript array of objects has the same value throughout 如何基于确定的属性值对JavaScript中的对象数组进行排序? - How to sort array of objects in JavaScript based on definite attribute value? 如何在javascript中基于相同的键和值合并两个对象数组? - How to Merge two array of objects based on same key and value in javascript? 如何根据对象数组中的键获取值 javascript - How to get value based on key from an array of objects javascript 如何根据数组对象javascript中的条件检查返回布尔值 - how to return boolean value based on condition check in array object javascript JavaScript 根据值减少对象数组 - JavaScript reduce array of objects based on value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM