[英]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.