![](/img/trans.png)
[英]Check if each object in array of objects contains a value that is in another array (JavaScript)
[英]Check if any object in an array of objects contains all of the key/value pairs in another object
我正在嘗試編寫一個查看對象數組(第一個參數)的函數,並返回包含給定對象(第二個參數)的所有鍵/值對的所有對象的數組。
我的代碼僅在source
對象(第二個參數)包含一個鍵/值對時才有效。 當source
對象具有兩個或更多鍵/值對時,結果不符合預期。
如何在source
對象中考慮多個鍵/值對?
function findObjects(collection, source) {
var result = [];
for (i=0; i<collection.length; i++) {
for (var prop in source) {
if (collection[i].hasOwnProperty(prop) && collection[i][prop] == source[prop]) {
console.log('Collection\'s object ' + [i] + ' contains the source\'s key:value pair ' + prop + ': ' + source[prop] + '!');
result.push(collection[i]);
} else {
console.log('fail');
}
}
}
console.log('The resulting array is: ' + result);
return result;
}
findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 });
// only the first object should be returned since it contains both "a":1 and "b":2
您可以使用一些數組方法,如Array#map
map()
方法創建一個新數組,其結果是在此數組中的每個元素上調用提供的函數。
every()
方法測試數組中的所有元素是否都通過了由提供的函數實現的測試。
首先使用Object.keys
獲取源代碼的屬性。
Object.keys()
方法返回給定對象自己的可枚舉屬性的數組,其順序與for...in
循環提供的順序相同(不同之處在於for-in循環枚舉原型鏈中的屬性為好)。
function findObjects(collection, source) { var keys = Object.keys(source); // get all properties of source return collection.filter(function (c) { // filter collection return keys.every(function (k) { // check every key return c[k] === source[k]; // compare value of collection and source }); }); } console.log(findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 }));
ES6語法相同(閱讀更多: 箭頭功能 )
基本上這種風格是簡短的寫作
function (x) { return y; }
成為
x => y
function findObjects(collection, source) { const keys = Object.keys(source); return collection.filter(c => keys.every(k => c[k] === source[k])); } console.log(findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 }));
function findObjects(collection, source) {
var result = [];
for (i=0; i<collection.length; i++) {
var matches = true;
for (var prop in source) {
if (!collection[i].hasOwnProperty(prop) || collection[i][prop] !== source[prop]) {
matches = false;
break;
}
}
if (matches) {
result.push(collection[i]);
}
}
return result;
}
基本上,你必須檢查所有性質,並確保它們匹配,然后才把你將它添加到您的result
陣列。
使用Object.keys
, Array.forEach
和Array.some
函數的解決方案:
function findObjects(arr, source) {
var keys = Object.keys(source), result = [];
arr.forEach(function(v){
!keys.some((k) => source[k] !== v[k]) && result.push(v);
});
return result;
}
console.log(findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 }));
// it will output [{"a":1,"b":2}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.