Javascript如何遍历对象以获取所选项目

时间:2017-08-20 21:53:28

标签: javascript

我想循环遍历data对象并从中挑选两个项目yearrevenue并将其放入新对象

var data [{"year": 2014, "revenue": 20000, "costs": 10000, "hours": 50}, {"year": 2015, "revenue": 30000, "costs": 20000, "hours": 54}, {"year": 2016, "revenue": 30000, "costs": 10000, "hours": 40}]

var pickedData = {};

data.forEach(output)

function output(d) {
     Object.assign({}, pickedData.Year = d.year),
     Object.assign({}, pickedData.Revenue = d.revenue)
}

代码可以工作,但只将data中的最后一项分配给新对象pickedData,这意味着它会将其循环,但不会在每次经过时为对象赋值。我怎么能有这样的输出:

console.log(pickedData)
 [{Year: 2014, Revenue: 20000}, {Year: 2015, Revenue: 30000}, {Year: 2016, Revenue: 30000}]

3 个答案:

答案 0 :(得分:2)

您可以使用{% if request.user in request.online_now %} {# do stuff #} {% endif %} 方法代替并返回新数组。



map()




答案 1 :(得分:1)

var pickedData = data.map(item => {
  return {
    Year: item.year,
    Revenue: item.revenue
  }
})

答案 2 :(得分:0)



var data = [{"year": 2014, "revenue": 20000, "costs": 10000, "hours": 50}, {"year": 2015, "revenue": 30000, "costs": 20000, "hours": 54}, {"year": 2016, "revenue": 30000, "costs": 10000, "hours": 40}];

var pickedDate = data.map(function(v,i,a){
  var retObj={};
  if(v.year) retObj.year = v.year;
  if(v.revenue != undefined) retObj.revenue=v.revenue;
  return retObj;
})

console.log(pickedDate);