如何过滤多维对象数组

时间:2019-06-17 11:28:30

标签: javascript json

GitHub issue #2807

我想考虑多个attribute值来过滤对象数组。使用复选框选择属性,我想使用这些值(例如RamPrimary camera)过滤数组。

我想像电子商务网站一样进行过滤:

var myObject = [
    {
        "ProId": 12,
        "ProName": "Samsung Galaxy A9",
        "AttriValue": {
            "Front Camera": "16 MP and Above",
            "Internal Memory": "128 GB and Above",
            "Network Type": "4G",
            "Primary Camera": "16 MP and Above",
            "Ram": "6 GB"
        }
    },
    {
        "ProId": 11,
        "ProName": "Vivo Y95",
        "AttriValue": {
            "Front Camera": "16 MP and Above",
            "Internal Memory": "64 GB",
            "Network Type": "4G",
            "Primary Camera": "13 - 15.9 MP",
            "Ram": "4 GB"
        }
    },
    {
        "ProId": 10,
        "ProName": "OPPO A7",
        "AttriValue": {
            "Front Camera": "16 MP and Above",
            "Internal Me...
        ....
     }
 ]

2 个答案:

答案 0 :(得分:1)

1。使用Javascript过滤器方法

filtered = myObject.filter(i => i.AttriValue.Ram === "4 Gb")

这样,您可以使用4GB内存过滤所有产品

2。使用for或while循环遍历myObject

filtered = []
for(let obj of myObject) {
  if(obj.AttriValue.RAM === '4 GB') filtered.push(obj)
}

答案 1 :(得分:0)

您可以使用filter

const myObject = [{
    "ProId": 12,
    "ProName": "Samsung Galaxy A9",
    "AttriValue": {
      "Front Camera": "16 MP and Above",
      "Internal Memory": "128 GB and Above",
      "Network Type": "4G",
      "Primary Camera": "16 MP and Above",
      "Ram": "6 GB"
    }
  },
  {
    "ProId": 11,
    "ProName": "Vivo Y95",
    "AttriValue": {
      "Front Camera": "16 MP and Above",
      "Internal Memory": "64 GB",
      "Network Type": "4G",
      "Primary Camera": "13 - 15.9 MP",
      "Ram": "4 GB"
    }
  },
]

const attrToFilter = {
  "Primary Camera": "13 - 15.9 MP",
  "Ram": "4 GB"
};

const filterFunction = (data, attrToFilter) =>
  data.filter(e =>
    Object.keys(attrToFilter)
    .map(i =>
      e.AttriValue[i] === attrToFilter[i]
    )
    .every(attr => !!attr)
  )

console.log(filterFunction(myObject, attrToFilter))


  

编辑

     

我已经更新了用于动态属性过滤的代码。

     

您可以在attrToFilter

中设置要过滤的属性。