删除json数组的某些部分

时间:2015-07-09 19:23:37

标签: javascript arrays json

我想基于某些值创建一个新的JSON数组。

示例JSON:

var array = 
{
    "entries": {
         "houses": [
              {
                 "category": {
                     "category_id":"1",
                     "category_foo":"bar",
                  },
                  "important": {
                      "important_foo":"bar",
                      "dontforget":"me",
                  }
               },
               {
                 "category": {
                     "category_id":"1",
                     "category_foo":"bar",
                  },
                  "important": {
                      "important_foo":"bar",
                      "dontforget":"me",
                  }
               },
                 "category": {
                     "category_id":"2",
                     "category_foo":"bar",
                  },
                  "important": {
                      "important_foo":"bar",
                      "dontforget":"me",
                  }
               }
            ]
       }
}

现在,我需要一种方法来搜索此数组,并创建一个包含houses category category_id=1的所有important的新数组。当然,它应该保留所有其他信息,如{ "entries": { "houses": [ { "category": { "category_id":"1", "category_foo":"bar", }, "important": { "important_foo":"bar", "dontforget":"me", } }, { "category": { "category_id":"1", "category_foo":"bar", }, "important": { "important_foo":"bar", "dontforget":"me", } } ] } }

新数组应如下所示:

select max(STR_TO_DATE(completion_date, '%m/%d/%Y %l:%i %p')) from test;

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用Array.filter执行此操作:

var filteredResults = array.entries.houses.filter(function(house) {
    return house.category && house.category_id == 1;
});

答案 1 :(得分:0)

此代码有效。

var houses = array.entries.houses;
var newHouses = [];
for (var i = 0; i < houses.length; i++)
{
     if (houses[i].category.category_id == "1") {
     newHouses.push(houses[i]);
     }
}

检查出来:https://jsfiddle.net/2u13phw3/