Anand
Anand

Reputation: 1699

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

Upvotes: 0

Views: 98

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386868

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);

Upvotes: 1

John Franke
John Franke

Reputation: 1535

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)

Upvotes: 1

Joel Lord
Joel Lord

Reputation: 2173

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);

Upvotes: 6

Related Questions