-3

I need to merge several arrays into one json and add a value but I'm stuck.
I have this:

    var areas = [];
    areas[0] = [];
    areas[1] = ["DE"];
    areas[2] = ["PL","BE","FR",];
    areas[3] = ["US"];  

and I need this:

values: {
  'DE': '#e6f2cc',
  'US': '#e6f2cc',
},  

So I need to merge the arrays and add "#e6f2cc" as a value to the key.
Is there a fast way to do that? I'm not a JS pro. I managed to merge it but I failed to add the value to this.
Thanks!

Marek123
  • 1,193
  • 7
  • 35
  • 75
  • [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Jun 27 '17 at 10:44
  • 1
    And by what logic do only two of those get such a color code assigned, but the value under areas[2] doesn’t? – CBroe Jun 27 '17 at 10:45

1 Answers1

1

Sure. Something like

var areas = [];
areas[0] = [];
areas[1] = ["DE"];
areas[2] = ["PL", "BE", "FR", ];
areas[3] = ["US"];

var merged = areas.reduce(function(obj, arr) {
  arr.forEach(function(value) {
    obj[value] = '#e6f2cc';
  });
  return obj;
}, {});

console.log(merged);

for instance.

The output (the value of merged) is

{ DE: '#e6f2cc',
  PL: '#e6f2cc',
  BE: '#e6f2cc',
  FR: '#e6f2cc',
  US: '#e6f2cc' }
user93
  • 1,866
  • 5
  • 26
  • 45
AKX
  • 152,115
  • 15
  • 115
  • 172