Dmap
Dmap

Reputation: 199

I want to return a JSON object from an array

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 : []};
  })

Upvotes: 2

Views: 707

Answers (3)

silversunhunter
silversunhunter

Reputation: 1259

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.

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386710

You could map entries and build an object from it.

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

console.log(object);

Upvotes: 5

epascarello
epascarello

Reputation: 207527

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

Upvotes: 1

Related Questions