gpt4 book ai didi

javascript - 在 a 中为每个对象创建对象及其对象属性

转载 作者:行者123 更新时间:2023-11-28 18:03:53 25 4
gpt4 key购买 nike

嗨,我想从已经有名称的对象的数组值创建属性。我的意思是我不想推送像 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"}] //...

最佳答案

您可以生成对象并将它们推送到结果集。

var arrayObjects = [],
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"],
i;

for (i = 0; i < dates.length; i++) {
arrayObjects.push({ date: dates[i] });
}

console.log(arrayObjects);

或者使用Array#map

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"],
arrayObjects = dates.map(function (a) {
return { date: a };
});

console.log(arrayObjects);

关于javascript - 在 a 中为每个对象创建对象及其对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43043067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com