让我们假设我有数组
a = ["hello", "world"]
我如何将其转换为
a = [
{ id : 1, value : "hello" },
{ id : 2, value : "world" }
]
这是我的解决方法
let a = ["hello", "world"]
const b = a.map((item, idx) => ({
id: idx + 1,
value: item
}))
console.log(b)
使用map方法:
const a = ["hello", "world"];
const b = a.map((item, index) => {
return { id: index + 1, value: item};
});
map
遍历数组。 map
返回一个新数组,并应用于每个项目转换a
转换(str, index) => ({id: index + 1, value: str})
的各项。 str
将从a
中获取每个项目,而index
将成为a
中的索引。返回具有属性Object
和id: index + 1
]的新value: str
var a = ["hello", "world"]
var b = a.map((str, index) => ({id: index + 1, value: str}))
console.log(b);