0

I have an array let labels = ['Apple', 'Banana', 'Pear'].

I want to map the array to a JSON output {'Apple':0, 'Banana':0, 'Pear':0}.

I am using the script:

let output = labels.map(function(item) {
  return { item: 0 };
});

which gives me:

[{"item": 0}, {"item": 0}, {"item": 0}]

How do I pass the variable item into the JSON output?

revvy
  • 151
  • 3
  • 16
  • 2
    use `return ({[item]: 0});`. – random Jan 05 '20 at 04:27
  • welcome. Placing `square brackets`, will retrieve value of the variable `item`, otherwise it will treat as a string. – random Jan 05 '20 at 04:35
  • @random I realised I made a mistake in the question. How do I get a JSON output as follow: `{"Apple": 0, "Banana": 0, "Pear": 0}`? I probably can't use .map() as it gives me an array? – revvy Jan 05 '20 at 04:49
  • No issues. use `reduce` which is more appropriate for converting `multiple into one object`-> `console.log(labels.reduce((a, item) => {a[item]=0; return a}, {}));` – random Jan 05 '20 at 04:56

0 Answers0