您能否帮我简化我将新属性添加到对象数组的方式
我有一个像这样的对象,
response.data = [ {'year':2015, 'month':1},
{'year':'2016','month':2}
];
我想添加一个新属性' monthName'
response.data = [{'year':2015, 'month':1,'monthName':'January'},
{'year':'2016','month':2,'monthName':'February'}
];
这就是我所做的,
var data = response.data; // Improvement
var ctr = 0;
$.each(response.data, function(a,b){
data[ctr].monthName = monthNumberToName(b.month);
ctr++;
});
return data;
你能帮我简化一下我的代码,谢谢!
答案 0 :(得分:1)
更简单的版本可能是
return response.data.map( s => Object.assign( {}, s, { monthName : monthNumberToName( s.month) } );
答案 1 :(得分:1)
您可以使用map
使代码看起来更短且易于管理:
var response = {};
response.data = [
{'year':2015, 'month':1},
{'year':'2016','month':2}
];
var data = response.data;
data.map((item)=>{
item.monthName = monthNumberToName(item.month);
});
function monthNumberToName(monthNumber){
if(monthNumber == 1){
return "January";
}
if(monthNumber == 2){
return "February";
}
}
console.log(response.data);

答案 2 :(得分:1)
您可以使用forEach
及其第一个参数:
const data = response.data;
data.forEach(d => d.monthName = monthNumberToName(d.month));
return data;
答案 3 :(得分:1)
function addProp(){
var data = res.data;
$.each(res.data, function(a,b){
//b is object and //a is the index
b.monthName = monthNumberToName(b.month);
});
return data;
}
答案 4 :(得分:1)
var monthNames = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ];
var response = {};
response.data = [
{'year':2015, 'month':1},
{'year':'2016','month':2}
];
response.data.map((item,key)=>{
item.monthName = monthNames[key];
});
答案 5 :(得分:0)
也许,你可以试试这个。
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'Septemper',
'October',
'November',
'December'
]
var data = [
{'year':2015, 'month':1},
{'year':'2016','month':2}
]
data = data.map(m=> {
m['monthName'] = months[m.month - 1]
return m
})
console.log(data)
答案 6 :(得分:-1)
calculator极大地帮助简化了代码。
你可以这样做:
保持一系列的月份:
const months = ["Jan","Feb", "Mar"];
let data = [ {'year':2015, 'month':1},
{'year':'2016','month':2}
];
_.forEach(data, function(value, key) {
value["monthName"] = months[value.month - 1];
});