如何切片JavaScript对象?

时间:2016-04-29 14:12:22

标签: javascript json

我有一个转换为JavaScript对象的JSON文件以及一个年份参数,我想只返回相关数组,并将其名称和内容作为JSON。

该文件如下所示:

{
"2012":[

    {
        "id": 1,
        "firstName": "John",
        "lastName": "Doe",
        "GPA": 80
    }    

],
"2013":[

    {
        "id": 1,
        "firstName": "John",
        "lastName": "Doe",
        "GPA": 85
    },
    {
        "id": 2,
        "firstName": "Anna",
        "lastName": "Smith",
        "GPA": 92
    }

]
}

我使用以下功能查找数组并使用GPA< 90删除所有已记录的数据:

  getExcellenceByYear: function(year) {   //get all students with GPA>=90 by year

        fake=JSON.parse(JSON.stringify(file));
        keys = Object.keys(fake);
        if(fake.hasOwnProperty(year))
        {

    for(var j=fake[year].length-1; j>=0; j--) // delete all irrelevant records
    {   
        if(fake[year][j].GPA<90)
        {
            delete fake[year][j];
            fake[year]=fake[year].filter(function(x) {return x!==null});
        }
    }


}
else
return JSON.stringify({});

return JSON.stringify(fake[year]);               
}

但是当我需要它时,我只返回数组中的记录,例如:

{
2013: [
{
   id: 2,
   firstName: "Anna",
   lastName: "Smith", 
   GPA: 92
}
  ]
}

由于

1 个答案:

答案 0 :(得分:3)

不是修改源数据,而是提取传递谓词的位。以下是使用Array.prototype.filter

的示例

&#13;
&#13;
var data = {
  "2012":[
      {
          "id": 1,
          "firstName": "John",
          "lastName": "Doe",
          "GPA": 80
      }    

  ],
  "2013":[
      {
          "id": 1,
          "firstName": "John",
          "lastName": "Doe",
          "GPA": 85
      },
      {
          "id": 2,
          "firstName": "Anna",
          "lastName": "Smith",
          "GPA": 92
      }
  ]
};

function getByYear(year, gpaThreshold) {
  if (!data[year]) {
    return null;
  }
  
  var obj = {},
      aboveGPAThreshold = data[year].filter(function(datum) {
        return datum.GPA >= gpaThreshold;
      });
  
  obj[year] = aboveGPAThreshold;
  
  return obj;
};

console.log(getByYear('2013', 90));
&#13;
&#13;
&#13;