簡體   English   中英

如何檢查對象數組是否完全屬於另一個?

[英]How to check an array of objects is totally belongs to another?

有兩個這樣的對象數組

var a = [
  {id:'1'},
  {id:'2'}
];
var b = [
  {id:'1',name:'a'},
  {id:'2',name:'b'},
  {id:'3',name:'c'}
]

我需要一個函數,如果可以在數組b中找到數組a的所有元素的id,它將返回true ,否則返回false

您可以使用Set並檢查Array#every

 const check = (a, b) => a.every((s => ({ id }) => s.has(id))(new Set(b.map(({ id }) => id)))); var a = [{ id: '1' }, { id: '2' }], b = [{ id: '1', name: 'a' }, { id: '2', name: 'b' }, { id: '3', name: 'c' }]; console.log(check(a, b)); 

這不是最有效的方法,因為它需要在創建ID列表b中的每個項目a

 var a = [ {id:'1'}, {id:'2'}, {id:'7'}, ]; var b = [ {id:'1',name:'a'}, {id:'2',name:'b'}, {id:'3',name:'c'} ] const allPresent = a .map(item => item.id) .map(id => Object.assign({ id, present: b .map(item => item.id) .indexOf(id) > -1, })) console.log(allPresent) 

您可以使用以下內容

 var a = [ {id:'1'}, {id:'2'} ]; var b = [ {id:'1',name:'a'}, {id:'2',name:'b'}, {id:'3',name:'c'} ] console.log(checkobject()); function checkobject() { var checkid=true; a.forEach(function(el) { var check=b.findIndex(function(element) { return element.id===el.id; }); if(check==-1) { checkid=false; return; } }); return checkid; } 

可以使用這種簡單的方法:

 var a = [ {id:'1'}, {id:'2'} ]; var b = [ {id:'1',name:'a'}, {id:'2',name:'b'}, {id:'3',name:'c'} ]; var id_a = a.map((current)=>{ return current.id; }); console.log(id_a); // ["1", "2"] var id_b = b.map((current)=>{ return current.id; }); console.log(id_b); // ["1", "2", "3"] // check if id_a in id_b, check total element of each set let bool = Array.from(new Set(id_b) ).length == Array.from(new Set(id_b.concat(id_a)) ).length; console.log(bool); 

使用Array.prototype.filterArray.prototype.some的解決方案:

 const includeCheck = (a, b) => { if (b.filter(el => a.some(obj => obj.id === el.id)).length === b.length) { console.log('b fully includes a') } else { console.log('b does not fully include a') } } let a = [{id:'1'}, {id:'2'}, {id:'3'}], b = [{id:'1',name:'a'}, {id:'2',name:'b'}, {id:'3',name:'c'}] includeCheck(a, b); 

它比較原始的長度b陣列和b通過過濾陣列a陣列的ID,以確定是否b具有所有a IDS或沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM