0

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

2
  • 2
    simple map loop Commented Sep 17, 2018 at 20:07
  • 4
    You can use map like this arr.map(name => ({name})). Commented Sep 17, 2018 at 20:09

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.