[英]Check if object already exists in object
我想通過僅擁有對象來檢查給定對象中是否已存在對象。 例如:
const information = {
...
city: {
Streetname: ''
}
}
現在,我得到了 city 對象並想檢查它是否已經在信息對象中(不知道屬性名稱)。 城市可能在信息對象的深處。
const contains = (item, data) => item === data || Object.getOwnPropertyNames(data).some(prop => contains(item, data[prop])); const information = { city: { Streetname: '' } } console.log(contains(information.city, information)); console.log(contains({}, information));
要獲取對象的屬性名稱,您可以使用Object.keys()
。 第一個問題解決了。
現在我們需要遍歷整個對象,包括嵌套對象。 這是第二個問題。
並將其與查詢對象進行比較。 這是第三個問題。
我假設我們有一個對象,它只包含具有原始值的“簡單”嵌套對象(我不考慮具有函數或數組的對象)
// let's assume we have this object
const information = {
city: {
Streetname: 'streetname1'
},
house: {
color: "blue",
height: 100,
city: {
findMe: { Streetname: '' } // we want to get the path to this property 'findMe'
}
},
findMeToo: {
Streetname: '' // we also want to get the path to this proeprty 'findMeToo'
},
willNotFindMe: {
streetname: '' // case sensetive
}
}
// this is our object we want to use to find the property name with
const queryObject = {
Streetname : ''
}
如果您使用===
比較Objects
您將始終按引用進行比較。 在我們的例子中,我們有興趣比較這些值。 如果您想對更復雜的對象執行此操作,則需要進行相當廣泛的檢查(有關詳細信息,請閱讀此 SO 注釋),我們將使用一個簡單的版本:
// Note that this only evaluates to true if EVERYTHING is equal.
// This includes the order of the properties, since we are eventually comparing strings here.
JSON.stringify(obj1) === JSON.stringify(obj2)
在我們開始實現我們的屬性探路者之前,我將介紹一個簡單的函數來檢查給定的值是一個對象還是一個原始值。
function isObject(obj) {
return obj === Object(obj); // if you pass a string it will create an object and compare it to a string and thus result to false
}
我們使用這個函數來知道什么時候停止深入研究,因為我們達到了一個不包含任何其他對象的原始值。 每次找到嵌套對象時,我們都會遍歷整個對象並深入研究。
function findPropertyPath(obj, currentPropertyPath) {
const keys = isObject(obj) ? Object.keys(obj) : []; // if it is not an Object we want to assign an empty array or Object.keys() will implicitly cast a String to an array object
const previousPath = currentPropertyPath; // set to the parent node
keys.forEach(key => {
const currentObj = obj[key];
currentPropertyPath = `${previousPath}.${key}`;
if (JSON.stringify(currentObj) === JSON.stringify(queryObject)) console.log(currentPropertyPath); // this is what we are looking for
findPropertyPath(currentObj, currentPropertyPath); // since we are using recursion this is not suited for deeply nested objects
})
}
findPropertyPath(information, "information"); // call the function with the root key
這將使用遞歸找到所有包含與您的查詢對象(按值進行比較)相等的對象的“屬性路徑”。
information.house.city.findMe
information.findMeToo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.