I want to return a JSON object from an array

Viewed 127

I have the following array.

numbers = ["1","2"]

I want to convert this array into the following object

numberList = {"1" : [], "2" : []}

I tried like following. but it does not work. I want to pass the number as a variable.

numbers.map( function(number) {
      return {number : []};
  })
3 Answers

You could map entries and build an object from it.

const
    numbers = ["1", "2"],
    object = Object.fromEntries(numbers.map(key => [key, []]));

console.log(object);

I think i would simply loop it and build the object

let numbers = ["1","2"];
let newObject = {};

for(let i=0; i < numbers.length; i++){
    newObject[numbers[i]] = [];
}

console.log(newObject);

The other answers here provide cleaner methods in my opinion. This is pretty old school.

You want to take your array and convert it into an object. To do that you want to use reduce.

numbers = ["1","2"]

var result = numbers.reduce( function (o, n) {
  o[n] = [];
  return o;
}, {});

console.log(result);

Related