[英]How to check if an object exists within another object using JS
假設我有一個對象數組
var arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
var obj1 ={name:'John', lastName:'Smith'};
如何使用JS檢查對象是否存在於另一個對象中?
嵌套循環會成功嗎? 第一個循環遍歷數組內部的對象,第二個循環遍歷對象內部的鍵/值對並將它們與obj1鍵/值對進行比較。 有一個更好的方法嗎 ? 還是我應該使用3個循環?
該函數應在包含obj1的arr中返回obj el。 例如:arr [0]應該返回,因為它包含obj1
function objInArr(srcArr, obj) {
var arr = [];
//var srcLength = 0;
//var sourceSize = Object.keys(source).length; // The length of the source obj
srcArr.forEach(function(el) {
el.forEach(function(objEl){
obj.forEach(function(sourceEl){
if( sourceEl === objEl) { arr.push(sourceEl); }
});
});
});
return arr;
}
您可以結合使用Arry#find()
和Array#some()
方法來遍歷數組對象,並查找是否存在具有相同鍵和值的對象:
var exists = arr.find(function(o){
return Object.keys(o).some(function(k){
return !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k];
});
});
如果存在,它將返回一個object
,如果要返回一個boolean
,則可以使用.find()
來更改.some()
。
這里的語句!Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k]
如果對象沒有迭代key
或它的value
不相同,則!Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k]
將退出。
演示:
var arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}]; var obj1 ={name:'John', lastName:'Smith'}; var exists = arr.find(function(o){ return Object.keys(o).some(function(k){ return !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k]; }); }); console.log(exists);
// object contains subObject
function partialContains(object, subObject) {
// Create arrays of property names
const objProps = Object.getOwnPropertyNames(object);
const subProps = Object.getOwnPropertyNames(subObject);
if (subProps.length > objProps.length) {
return false;
}
for (const subProp of subProps) {
if (!object.hasOwnProperty(subProp)) {
return false;
}
if (object[subProp] !== subObject[subProp]) {
return false;
}
}
return true;
}
您現在可以像這樣使用它:
const arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
const obj1 ={name:'John', lastName:'Smith'};
const containing = arr.find((object) => partialContains(object, obj1));
如果containing
未定義,什么也沒有找到,否則,包含對象obj1
返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.