[英]How to convert array to object with add same key in this object Javascript?
I am trying to convert this array to object with same custom key我正在尝试使用相同的自定义密钥将此数组转换为 object
let array=['a','b','c']
let y= Object.assign({}, [...array]);
I want resualt like this我想要这样的结果
[{'name':'a'},{'name':'b'},{'name':'c'}]
how I can do this?我怎么能这样做?
You can use Array.map.您可以使用 Array.map。 Here it is.这里是。
let array=['a','b','c'] const res = array.map(item => ({name: item})) console.log(res)
Why haven't you tried a simple for loop yet:为什么你还没有尝试过一个简单的 for 循环:
let array=['a','b','c'] let ans = []; //initialize empty array for(let i = 0; i < array.length; i++){ //iterate over initial array ans.push({name: array[i]}); //push in desired format } console.log(ans);
For example.例如。 With map()
or loops like for...
or forEach
you can do it.使用map()
或for...
或forEach
之类的循环,您可以做到。
array=['a','b','c'] let res1 = array.map(a => ({name: a})) console.log('map()', res1) // or forEach let res2 = []; array.forEach(a => { res2.push( {name: a}) }) console.log('forEach()', res2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.