简体   繁体   中英

Convert array to object list in javascript

Is there a function that can convert an array ['A', 'B', 'C'] to an object array [{name: 'A'}, {name: 'B'}, {name: 'C'}] ?

Or do I need to write a util function? It is no big deal to write one but curious if a well known function is already there.

Thanks

You can use Array.prototype.map(). Array.map is a method that will iterate through each element in an Array and return an output based on the callback. You can find more information on Array.map on the MDN: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map

And here is a working example: https://jsbin.com/qawener/edit?js,console

In this example, we take each element of the array and we return an object with {"name": }. This then creates the newArray array that will have [{name: 'A'}, {name: 'B'}, {name: 'C'}] .

const originalArray = ["a", "b", "c"];

let newArray = originalArray.map(element => { return {name: element}; });


console.log(newArray);

Map works very well for these types of situations.

const array = ['A', 'B', 'C'];
const myNewArray = array.map(function(map, i) {
     const dict = {"name":array[i]}    
     return dict;
}, {});

console.log(myNewArray)

Beside the given answer, you may use short hand properties for the object.

 const names = ["a", "b", "c"], result = names.map(name => ({ name })); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM