2

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 : []};
  })
4
  • reduce, not map Commented Mar 18, 2021 at 18:16
  • 2
    benalman.com/news/2010/03/theres-no-such-thing-as-a-json Commented Mar 18, 2021 at 18:17
  • 1
    JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. Commented Mar 18, 2021 at 18:17
  • numbers.map( function(number) { return {[number] : []}; }) Commented Mar 18, 2021 at 18:24

3 Answers 3

5

You could map entries and build an object from it.

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

console.log(object);

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

Comments

3

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.

3 Comments

Or even for (const number of numbers) { newObject[number] = []; } (And agreed on the loop. :-) Or fromEntries as Nina shows.)
I am realizing with all these answers there are cleaner ways to do this.
Oh, a simple loop is nice, clean, clear, and efficient IMHO. I certainly wouldn't use reduce. Overcomplicated and easy to get wrong.
1

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

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.