[英]how to turn array into array of objects
I am working with an array of words for example:我正在处理一系列单词,例如:
const words = ["hello", "world", "how", "are", "you"] const words = [“你好”,“世界”,“怎么样”,“是”,“你”]
How can I transform this into an array of objects:如何将其转换为对象数组:
const words1 = [ {0: "hello"}, {1: "world"},; {2: "how"}, {3: "are"}, {4: "you"} ]
Use map
& return an object where key is the index
and its value will be each item from the original array使用
map
并返回一个对象,其中键是index
,其值将是原始数组中的每个项目
const words = ["hello", "world", "how", "are", "you"]; let result = words.map(function(item, index) { return { [index]: item } }); console.log(result)
If you are trying with normal for
loop then create an empty array and push object to it.如果您尝试使用普通
for
循环,则创建一个空数组并将对象推送到它。 Note the way i
is placed inside []
注意
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)
Here you go.干得好。 Run the code and you'll see the result you're looking for printed out.
运行代码,您将看到打印出的结果。
NOTE: This will work in older browsers and versions of JS.注意:这适用于较旧的浏览器和 JS 版本。 Solutions with { [index] : ... } will not.
带有 { [index] : ... } 的解决方案不会。
const words = ["hello", "world", "how", "are", "you"]; var obj; for( let i=0; i < words.length; i++ ) { obj = {}; obj[i] = words[i] words[i] = obj; } document.write( JSON.stringify( words ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.