2

I am trying to convert an array of numbers to array of objects. What is the easiest way to do this?

myArray = [1,2,3];

myObject = convertToObjects(myArray);

convertToObjects= (items) => {
    let listOfItems = [];
    let convertToObj = items.map(item, idx => {
      let key = item;
      listOfItems.push({ key });
    });
    return listOfItems;
  }

Thank you!

Expected output:

[
{key: 1},
{key: 2},
{key: 3}]
2
  • 2
    MDN map Commented Jan 10, 2017 at 20:58
  • 6
    myArray.map(x => ({key:x})) Commented Jan 10, 2017 at 20:58

3 Answers 3

1

You could map the object.

var myArray = [1, 2, 3],
    convertToObjects = items => items.map(key => ({ key })),
    myObject = convertToObjects(myArray);

console.log(myObject);

Sign up to request clarification or add additional context in comments.

Comments

1

@qxz provided an answer in the comments

myArray.map(x => ({key:x}))

Here is a brief explanation.

map() is a function of Arrays. It calls a provided callback function for each element, then returns an Array of the results. See the documentation for map()

map() returns an array, rather than modifying it in place, so you'll need to capture the result.

var myArray = [1, 2, 3],
var convertedArr = myArray.map( function(item) {
    return {"key": item};
});

console.log(convertedArr);

Comments

1

map function has as parameter a callback function.

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

Read more about map method.

Try this:

myArray = [1,2,3];

myObject = convertToObjects(myArray);

function convertToObjects(items){
    let listOfItems = [];
    let convertToObj = items.map(function(item) {
      let key = item;
      listOfItems.push({ key });
    });
    return listOfItems;
  }
console.log(myObject);

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.