我想循环遍历data
对象并从中挑选两个项目year
和revenue
并将其放入新对象
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}]
答案 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);