简体   繁体   English

在 JavaScript 中过滤嵌套对象

[英]Filter Nested Object in JavaScript

This code snippet works to just filter array of objects using a string value.此代码片段仅使用字符串值过滤对象数组。

So how can I make the code snippet cater for a nested object, so that it can filter both array of objects as well as a nested object within?那么如何使代码片段适合嵌套对象,以便它可以过滤对象数组以及其中的嵌套对象?

mainLogic = (_data, search) => {
   //_data is an array of objects
    let _allsearch = search.trim().toLowerCase();
    if (_allsearch.length > 0) {
      _data = Object.values(_data).filter((obj) => {
        return Object.keys(obj).some((key) => {
       // the code usually breaks at this point. when it encounters a nested object
            return obj[key].toLowerCase().includes(_allsearch); 
        });
      });
    }
    return _data;

  };

This is a sample object:这是一个示例对象:

let _data = [
  {
    id: "1",
    firstname: "Precious",
    lastname: "Same",
    age: "29",
    state: "Abia",
    email: "sam@gmail.com",
    country: "Michigan",
    town:{
      name:"Jos"
    }
  },
  {
    id: "2",
    firstname: "Bolu",
    lastname: "Joke",
    age: "32",
    state: "Ogun",
    email: "bolu.joke@outlook.com",
    country: "america",
    town:{
      name:"California"
    }
  }
]

When calling the function:调用函数时:

this.mainLogic(_data, "california")

This is what I expect:这是我的期望:

[
  {
    id: "2",
    firstname: "Bolu",
    lastname: "Joke",
    age: "32",
    state: "Ogun",
    email: "bolu.joke@outlook.com",
    country: "america",
    town:{
      name:"Califonia"
    }
  }
]

Disclaimer: Code mainly derived from here免责声明:代码主要来源于这里

I would just flatten the object, so that every property is on the same level and you do not need to cater for nested objects.我只是将对象展平,这样每个属性都在同一级别上,您不需要满足嵌套对象的需求。 After that, filtering is done the same way you are doing it now.之后,过滤的方式与您现在的方式相同。 (Left out verification and error checking, you can adapt your code) (省略验证和错误检查,您可以调整您的代码)

 let data = [{ id: "1", firstname: "Precious", lastname: "Same", age: "29", state: "Abia", email: "sam@gmail.com", country: "Michigan", town: { name: "Jos" } }, { id: "2", firstname: "Bolu", lastname: "Joke", age: "32", state: "Ogun", email: "bolu.joke@outlook.com", country: "america", town: { name: "California" } } ]; function flattenObject(ob) { var toReturn = {}; for (var i in ob) { if (!ob.hasOwnProperty(i)) continue; if ((typeof ob[i]) == 'object') { var flatObject = flattenObject(ob[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = ob[i]; } } return toReturn; }; function mainLogic(data, search) { for (let obj of data) { flattened = flattenObject(obj); if (Object.values(flattened).includes(search)) return obj; }; }; console.log(mainLogic(data, "California"))

It is necessary to flat object, then array could be easily filtered:有必要扁平化对象,然后可以轻松过滤数组:

_data.forEach((el, i) => {
  let flattenedObject = flatObject(el);
  if (Object.values(flattenedObject).includes(searchWord))
    _data = _data.filter((f, ind) => ind == i);
})

An example:一个例子:

 let _data = [ { id: "1", firstname: "Precious", lastname: "Same", age: "29", state: "Abia", email: "sam@gmail.com", country: "Michigan", town:{ name:"Jos" } }, { id: "2", firstname: "Bolu", lastname: "Joke", age: "32", state: "Ogun", email: "bolu.joke@outlook.com", country: "america", town:{ name:"California" } } ]; const flatObject = (obj) => { return Object.assign( {}, ...function _flatten(o) { return [].concat(...Object.keys(o) .map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]}) ) ); }(obj) ) } let searchWord = 'California'; _data.forEach((el, i) => { let flattenedObject = flatObject(el); if (Object.values(flattenedObject).includes(searchWord)) _data = _data.filter((f, ind) => ind == i); }) console.log(_data);

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

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