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?
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?
Share Improve this question asked Jun 24, 2014 at 11:10 RamkumarRamkumar 4561 gold badge14 silver badges32 bronze badges 4-
2
You are currently just putting all keys in an array and all values in another -- the Output is actually
[abc,def] [1,40]
. – user887675 Commented Jun 24, 2014 at 11:16 - Its because JS expects every key in the array to be unique. This wouldnt work out of the box. If you change def's to 3 different keys, it works perfectly. – paradox Commented Jun 24, 2014 at 11:18
-
1
var a = {"abc": 1, "def": 2, "def": 42, "def" : 40};
actually produces Object {abc: 1, def: 40}. How are you actually getting your array values initially? – JamesA Commented Jun 24, 2014 at 11:20 - 2 @Maniram, can't you change the structure to this: {"abc": [1], "def": [2, 42, 40]} ? – user2575725 Commented Jun 24, 2014 at 11:26
2 Answers
Reset to default 6You 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
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.