0

在此处输入图像描述

我想过滤一个考虑多个attribute值的对象数组。使用复选框选择属性,我想使用这些值(例如,,)过滤Ram数组Primary 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...
        ....
     }
 ]
4

2 回答 2

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)
}
于 2019-06-17T11:52:37.347 回答
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

于 2019-06-17T11:51:20.190 回答