检查对象中是否已存在对象

时间:2019-02-10 00:48:27

标签: javascript

我想通过仅具有对象来检查给定对象中是否已存在对象。 例如:

const information = {
    ...
    city: {
        Streetname: ''
    }
}

现在,我得到了city对象,并想检查它是否已经在信息对象中(不知道属性名称)。该城市可能位于信息对象的深处。

2 个答案:

答案 0 :(得分:0)

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));

答案 1 :(得分:0)

要获取对象的属性名称,可以使用from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.floatlayout import FloatLayout class TestLayer(FloatLayout): def __init__(self, **kwargs): super(TestLayer, self).__init__(**kwargs) self.pos_hint = {'top': 1, 'x': 0} self.size_hint_x = 1 self.size_hint_y = 1 print('center_0 : %s, %s' % (self.center_x, self.center_y)) # >> center_0 : 50, 50 # How to get 'center_1' at this def without using 'on~' event? class TestScreen(Screen): def __init__(self, **kwargs): print('init TestScreen') super(TestScreen, self).__init__(**kwargs) self.layer = TestLayer() self.add_widget(self.layer) def on_enter(self, *args): print('center_3 : %s, %s' % (self.layer.center_x, self.layer.center_y)) sm = ScreenManager(transition=NoTransition()) # start with no transition for speed (can change it later) class DemoApp(App): def build(self): sm.add_widget(Screen(name='first')) # start with a dummy 'first' Screen sm.add_widget(TestScreen(name='test')) sm.current = 'test' # switch to the 'test' Screen return sm if __name__ == '__main__': DemoApp().run() 。第一个问题解决了。
现在我们需要遍历包括嵌套对象在内的整个对象。这是第二个问题。
并将其与查询对象进行比较。这是第三个问题。

我假设我们有一个只包含“简单”对象的对象,尽管带有原始值的嵌套对象(我不考虑具有函数或数组的对象)

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 : '' } 比较===,则将始终按引用进行比较。在我们的案例中,我们有兴趣比较这些值。如果要对更复杂的对象进行检查,则涉及到相当广泛的检查(有关详细信息,请阅读this SO comment),我们将使用简单的版本:

Objects

在开始实现属性探路器之前,我将介绍一个简单的函数来检查给定值是Object还是原始值。

// 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