嗨,我想从已经具有名称的对象的数组值创建属性。我的意思是我不想推送诸如push({date:// whatever})之类的匿名对象。
这是我的代码:
var obj= {}
var arrayObjects= []
var dates= ["Mar 02, 2017", "Mar 02, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017"]
for(var i=0; i< dates.length; i++){
arrayObjects.push( obj["date"]= dates[i])
}
但是我只知道arrayObjects的日期:
["Mar 02, 2017", "Mar 02, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017"]
我想要的是obj数组,其中包含数组中的每个日期,例如:
[Object {date: "Mar 01, 2017"}, Object {date: "Mar 02, 2017"}] //...
最佳答案
使用Array#reduce
。
var dates = ["Mar 02, 2017", "Mar 02, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017", "Mar 01, 2017"],
result = dates.reduce(function(s,a){
var obj = {};
obj.date = a;
s.push(obj);
return s;
}, []);
console.log(result);