如何将数组变成对象数组

时间:2019-03-12 17:15:44

标签: javascript arrays object

例如,我正在处理一组单词:

常量词= [“你好”,“世界”,“如何”,“是”,“你”]

如何将其转换为对象数组:

const words1 = [ {0: "hello"}, {1: "world"},; {2: "how"}, {3: "are"}, {4: "you"} ]

2 个答案:

答案 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)