过滤JSON Obj

时间:2017-10-02 20:23:28

标签: javascript json

我从XMLHttpRequest获取了一个JSON对象,正在寻找过滤bt genre的解决方案。如果没有传递过滤参数,我还需要一种方法来返回所有结果(未经过滤)。

app.js(伪函数)

function filterObject(json, filterBy) {
  // filter through json
  // return item that matches filterBy
}

data.json

[{
  "date": {
    "dayOfWeek": "Thursday",
    "month": "Oct"
  },
  "location": "Bristol",
  "genre": "rock"
}, {
  "date": {
    "dayOfWeek": "Cardiff",
    "dayOfMonth": 13,
    "month": "Oct"
  },
  "location": "Manchester",
  "genre": "jazz"
}]

3 个答案:

答案 0 :(得分:2)

您可以使用array#filter过滤genre值上的json。



var json = [{"date": {"dayOfWeek": "Thursday","month": "Oct"},"location": "Bristol","genre": "rock"}, {"date": {"dayOfWeek": "Cardiff","dayOfMonth": 13,"month": "Oct"},"location": "Manchester", "genre": "jazz"}];

function filterObject(json, filterBy) {
  return filterBy ? json.filter(o => o.genre === filterBy) : json;
}

console.log(filterObject(json,'jazz'));

console.log(filterObject(json));

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

您可以使用Array#filter

这样的事情:

(function() {
  var json = [{
    "date": {
      "dayOfWeek": "Thursday",
      "month": "Oct"
    },
    "location": "Bristol",
    "genre": "rock"
  }, {
    "date": {
      "dayOfWeek": "Cardiff",
      "dayOfMonth": 13,
      "month": "Oct"
    },
    "location": "Manchester",
    "genre": "jazz"
  }];

  function filterObject(json, filterBy) {
    if (filterBy !== undefined) {
      return json.filter(function(x) {
        return x.genre === filterBy;
      });
    } else {
      return json;
    }
  }
  var resultWithParameter = filterObject(json, "jazz");
  console.log(resultWithParameter);

  var resultWithoutParameter = filterObject(json);
  console.log(resultWithoutParameter);
})();

答案 2 :(得分:1)

您可以将filterBy用作具有键和值属性的对象,以查找您喜欢的任何属性(不仅仅是流派键)。

   function filterObject(data, filterBy) {
    if(typeof filterBy === 'undefined') return data;
     return data.filter(function(item) {
      return item[filterBy.key] === filterBy.value;
     })
   }

测试:

  filterObject(arr, {key: 'genre', value: 'rock'}); // return rock band
  filterObject(arr, {key: 'genre', value: 'jazz'}); // jazz band
  filterObject(arr, {key: 'location', value: 'Bristol'}); // return band with location key
  filterObject(arr); // return initial array