Ramkumar
Ramkumar

Reputation: 456

Add array values into map using javascript?

I have an array value as a with key:value pair. I wanted to map the same key array values as below format:

Expected Output: [abc: 1],[def:2,42,40]

Please find my code below:

var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};    
var array_keys = new Array();
var array_values = new Array();
for (var key in a) {
    array_keys.push(key);
    array_values.push(a[key]);
}
alert(array_keys);
alert(array_values);

It returns the values as

My output : [abc:def] [1,40]

Any help on this?

Upvotes: 5

Views: 33912

Answers (2)

Andy
Andy

Reputation: 63587

You can achieve something like what you want if you play around with your initial data structure:

Have an array of objects:

var a = [{abc: 1}, {def: 2}, {def: 42}, {def: 40}];

Set up a new object

var o = {};

And then loop over the data. For each object: if the key doesn't exist in o, the output object, add it and set its value to an array, otherwise just push the value of the object to the array.

for (var i = 0, l = a.length; i < l; i++) {
  var key = Object.keys(a[i]);
  if (!o[key]) { o[key] = []; }
  o[key].push(a[i][key]);
}

And you end up with an object the values of which are arrays:

console.log(o); // {abc: [1], def: [2,42,40] }

Demo

Upvotes: 6

Michael Kunst
Michael Kunst

Reputation: 2988

var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};

This is not possible. Object keys must be unique in javascript, so you can't add 3 different items with the same key ("def"). If you define multiple elements with the same key, at least chrome will take the last added value.

So answering your question: With the input provided there is no way to get you Expected output.

Upvotes: 2

Related Questions