Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用嵌套数据过滤JSON––;JavaScript_Javascript_Arrays_Json - Fatal编程技术网

使用嵌套数据过滤JSON––;JavaScript

使用嵌套数据过滤JSON––;JavaScript,javascript,arrays,json,Javascript,Arrays,Json,我创建了一个脚本,用于过滤JSON数据并返回正确的数据对象。然而,JSON数据现在已经改变,我需要通过包含数组的JSON进行过滤 我将解释我的代码: 这里是我们的JSON数据 const products = [ { "id": 1, "title": "baz", "application": "Snow", "usage": "

我创建了一个脚本,用于过滤JSON数据并返回正确的数据对象。然而,JSON数据现在已经改变,我需要通过包含数组的JSON进行过滤

我将解释我的代码:

这里是我们的JSON数据

const products = [
  {
    "id": 1,
    "title": "baz",
    "application": "Snow",
    "usage": "Domestic",
    "drive": "Pedestrian",
    "price": "1190.00"
  },
  {
    "id": 2,
    "title": "bar",
    "application": "Animal feed or waste",
    "usage": "Domestic",
    "drive": "Ride on",
    "price": "4495.00"
  },
  {
    "id": 3,
    "title": "foo",
    "application": "Snow",
    "usage": "Commercial",
    "drive": "Ride on",
    "category": "Compact Tractor",
    "price": "2650.00"
  },...
]
我使用这个过滤器函数,它接受我们传入的JSON数组和过滤器

function filterArray(array, filters) {
  if (array) {
    const filterKeys = Object.keys(filters);
    return array.filter((item) => {
      return filterKeys.every((key) => {
        if (typeof filters[key] !== 'function') return true;
        return filters[key](item[key]);
      });
    });
  }
}
例如,我在下面的变量中设置了静态数据,在现实生活中,这些数据来自单击的任何输入值

const first = 'Snow',
      second = 'Domestic',
      third = 'Pedestrian'


const filtersObject = {
  application: (application) => application === first,
  usage: (usage) => usage === second,
  drive: (drive) => drive === third
};

console.log(filterArray(products, filtersObject));
更新后的JSON数据如下所示:

const products = [
  {
    "id": 1,
    "title": "baz",
    "application": ["Snow"],
    "usage": ["Domestic"],
    "drive": ["Pedestrian", "Ride on"],
    "price": "1190.00"
  },
  {
    "id": 2,
    "title": "bar",
    "application": ["Animal feed or waste", "Snow"],
    "usage": ["Commercial", "Domestic"],
    "drive": ["Ride on"],
    "price": "4495.00"
  },
  {
    "id": 3,
    "title": "foo",
    "application": ["Animal feed or waste", "Snow"],
    "usage": ["Commercial", "Domestic"],
    "drive": ["Ride on"],
    "category": "Compact Tractor",
    "price": "2650.00"
  }
]
我很难用阵列来实现这一点。任何帮助都将不胜感激

请看我的