首页 > 解决方案 > 如何过滤多维数组对象

问题描述

我想过滤这个数组attributevalue,例如,如果我按蓝色进行搜索,那么所有衬衫都给我蓝色,然后我搜索蓝色的织物棉然后给所有蓝色的棉布,你知道搜索像 Flipkart,亚马逊

var myObject=    [
                {
                    "Product-name": "Shirt",
                    "product-price": "500",
                    "attributevalue": [
                        { "color": "red" },
                        {"fabric": "cottton"}
                    ]
                },
                {
                    "Product-name": "Samsung mobile",
                    "product-price": "15000",
                    "attributevalue":[
                        {"Ram": "4 GB"},
                        {"Network": "4G"},
                        {"Primary Camera": "8 MP"},
                        {"Internal Memory": "8 GB"}
                    ]
                }
            ]

标签: javascriptjson

解决方案


您可以结合filter,forfor...in做到这一点:

var myObject=    [
                {
                    "Product-name": "Shirt",
                    "product-price": "500",
                    "attributevalue": [
                        { "color": "red" },
                        {"fabric": "cottton"}
                    ]
                },
                {
                    "Product-name": "Samsung mobile",
                    "product-price": "15000",
                    "attributevalue":[
                        {"Ram": "4 GB"},
                        {"Network": "4G"},
                        {"Primary Camera": "8 MP"},
                        {"Internal Memory": "8 GB"}
                    ]
                }
            ]
            
 const search = (arr, search) => {
  return arr.filter(item => {
    for (var i = 0; i < item.attributevalue.length; i++) {
      for (var key in item.attributevalue[i]) {
        if (item.attributevalue[i][key].toLowerCase() === search.toLowerCase()) {
          return item;
        }
      }
    }
   })
 }
 
 console.log(search(myObject, 'red'))


推荐阅读