例如,我正在处理一组单词:
常量词= [“你好”,“世界”,“如何”,“是”,“你”]
如何将其转换为对象数组:
const words1 = [ {0: "hello"}, {1: "world"},; {2: "how"}, {3: "are"}, {4: "you"} ]
答案 0 :(得分:2)
您可以使用map
const words = ["hello", "world", "how", "are", "you"]
let op = words.map((value,key) => ({[key]: value}))
console.log(op)
答案 1 :(得分:0)
使用map
并返回一个对象,其中键为index
,其值将是原始数组中的每个项目
const words = ["hello", "world", "how", "are", "you"];
let result = words.map(function(item, index) {
return {
[index]: item
}
});
console.log(result)
如果您尝试使用普通的for
循环,则创建一个空数组并将对象压入其中。请注意i
在[]
内的放置方式
const words = ["hello", "world", "how", "are", "you"];
let newArray = [];
for (let i = 0; i < words.length; i++) {
newArray.push({
[i]: words[i]
})
}
console.log(newArray)