Filtering array of objects by searching nested object properties

后端 未结 6 717
执笔经年
执笔经年 2020-12-06 07:38

I have an array of objects that I want to filter by comparing a nested property to a search term.

For example:

 var array = [
      {category: \'Bus         


        
6条回答
  •  时光说笑
    2020-12-06 08:08

    Note: I am taking a shortcut-like approach to this, primarily to provide a different perspective to the problem.

    Instead of deep-searching the properties and arrays under the main array, you can create a json string of the users property and search within that. So I have created a new property usersString that temporarily stores the JSON string of the value against users property.

    item.usersString = JSON.stringify(item.users);
    

    Now, this would not be a perfect implementation, but it would almost always work. Also, if you stored this property within the browser (without storing it back to the DB), and used it to quick-search for every time user searches, I think it would be more performant that deep-searching entire array.

    var array = [{
        category: 'Business',
        users: [{
            name: 'Sally',
            tags: [{
              tag: 'accounting'
            }, {
              tag: 'marketing'
            }]
          },
          {
            name: 'Bob',
            tags: [{
              tag: 'sales'
            }, {
              tag: 'accounting'
            }]
          }
        ]
      },
      {
        category: 'Heritage',
        users: [{
            name: 'Linda',
            tags: [{
              tag: 'Italy'
            }, {
              tag: 'Macedonia'
            }]
          },
          {
            name: 'George',
            tags: [{
              tag: 'South Africa'
            }, {
              tag: 'Chile'
            }]
          }
        ]
      }
    ];
    
    var key = "market";
    
    // Convert the users property into a string - so that it works as a quick search target.
    array.forEach(function(item) {
      item.usersString = JSON.stringify(item.users);
    });
    
    
    var filteredItems = array.filter(function(item) {
      return item.usersString.toLowerCase().indexOf(key.toLowerCase()) >= 0;
    });
    
    // Delete the usersString property - if required.
    filteredItems.forEach(function(item) {
      item.usersString = undefined;
      // Or,
      // delete item.usersString;
    })
    
    console.log(filteredItems);

提交回复
热议问题