简体   繁体   English

如何将数组转换为 object 并在此 object Javascript 中添加相同的密钥?

[英]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.

相关问题 如何在JavaScript中使用特定键将数组转换为对象 - how convert array to object with specific key in javascript 如何在JavaScript中将具有属性和键的对象转换为Array? - How to convert an object with property and key to Array in JavaScript? 如何比较两个对象数组,如果值相同,则添加新键:Javascript 中第二个对象的值 - How to compare two array of object and if value are same add new key: value on second object in Javascript 将两个数组转换为一个对象,Javascript中每个数组的键相同 - Convert two arrays to one object, with same key for each array in Javascript Javascript:将对象添加到具有相同键的现有对象数组不起作用 - Javascript: Add object to Existing Array of objects with the same key not working 如何在javascript中更改嵌套数组对象键和相同的数组 - how to change the nest array object key and same array in javascript 如何将 React 数组转换为具有相同键和值的 JSON 对象? - How to convert a React array to a JSON object with same key and value? 如何通过键将数组转换为对象? - How to convert array to object by key? 将字符串数组转换为具有相同键/值的 object - Convert string array into object with same key/value 如何在 object 数组中的相同 object 中添加相同键的键值对? - how to add key value pair for same key in same object in array of object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM