如何在JSON中选择一些属性

时间:2016-10-19 06:09:39

标签: json

以下是数据:

var data1 = [{
"Date": "2016-07-09",
"H1_PNL2": 20, 
"H1_NAV2" : 20
"H2_PNL2": 20, 
"H2_NAV2" : 20,
"NAV": 26.28,
"PNL": 7.61
}, {
"Date": "2016-07-10",
"H1_PNL2": 20, 
"H1_NAV2" : 20
"H2_PNL2": 20, 
"H2_NAV2" : 20,
"NAV": 27.55,
"PNL": 12.89
}];

如果我只想选择DateH2_PNL2

var data1 = [{
"Date": "2016-07-09",
"H2_PNL2": 20, 
}, {
"Date": "2016-07-10",
"H2_PNL2": 20, 
}];

如何选择我想要的特定属性?

1 个答案:

答案 0 :(得分:2)

使用Array.prototype.map遍历数组,然后为每个对象构造一个只包含您感兴趣的属性的新对象:

data1.map(o => ({ Date: o.Date, H2_PNL2: o.H2_PNL2 }));

编辑:删除属性可以有两种方式,具体取决于您是否要保留原始属性。

破坏性:

data1.forEach(o => { delete o.NAV; delete o.PNL; });

无损:

data1.map(o => {
  var c = Object.assign({}, o);
  delete c.NAV; delete c.PNL;
  return c;
});