简体   繁体   English

如何按属性在嵌套的 object 中搜索 object 并返回 object 与父对象的键和值?

[英]How to search object in nested object by property and return object with parent object's key and value?

I have a nested object我有一个嵌套的 object

let data = {
  address: "123 Street, state, country",
  childObject1: {
    foo: ["bar"],
    person: "Hailey"
  },
  relatedCustomers: {
    childObject: {
      foo: ["bar"],
      person: "Hailey2"
    }
  }
};

I want to search object with keys and values by property.我想按属性搜索带有键和值的 object。

For example例如

search - my function搜索 - 我的 function

data - nested object数据 - 嵌套 object

search("person", data)

I get the object我得到 object

{
  childObject: "Hailey2",
  childObject1: "Hailey"
}

I write the code which search all values with person:我编写了用人搜索所有值的代码:

https://codesandbox.io/s/suspicious-pascal-qyvjw https://codesandbox.io/s/suspicious-pascal-qyvjw

but I can't get parent object key and get object as a result:但我无法获得父 object 密钥并获得 object 结果:

{
  childObject: "Hailey2",
  childObject1: "Hailey"
}

Please use following code to find the parent key:请使用以下代码查找父键:

let search = (needle, parentKey, haystack, found = []) => {
  Object.keys(haystack).forEach(key => {
    if (key === needle) {
      found.push({
        [key]: haystack[key],
        parentKey
      });
      return found;
    }
    if (typeof haystack[key] === "object") {
      search(needle, key, haystack[key], found);
    }
  });
  return found;
};

console.log(search("person", "data", data));
`;

I have just passed the parent key in the function and saved it if required.我刚刚传递了 function 中的父密钥,并在需要时保存了它。 I hope this is what you are looking for.我希望这就是你要找的。 Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM