Reputation: 199
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
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
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
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