I have this JSON
[ {"key":"main1","value":320}, {"key":"main2","value":240}, {"key":"front1","value":220}, {"key":"main1","value":300}, {"key":"main2","value":240}, {"key":"front1","value":120}, {"key":"front5","value":120} ]
And need transform like this, get it off when they have same key and create array from same values.
[ {"main1": [320, 300]}, {"main2": [240, 240]}, {"front1": [220, 120]}, {"front5": [120]} ]
Asked
Active
Viewed 56 times
-2

parucker
- 361
- 1
- 2
- 10
-
What is the question? – R3tep Mar 11 '15 at 14:31
-
3There is no question. The OP is asking us to do all the work for him. OP, that's not how SO works, I'm afraid. You need to show, at the minimum, the work you've already tried. Please post your code in your question. – Andy Mar 11 '15 at 14:34
-
even tried map and reduce? – Pavel Gatnar Mar 11 '15 at 14:38
-
Right, sorry for don't put all my code, Im doing with backbone if I put all the work here, the post would be to much big, cause I need to do alot forEachs to get this json, so I tried to being more practical and I am very noobie here sorry. – parucker Mar 11 '15 at 14:55
1 Answers
2
You could do it like this :
var element,
result = {},
test = [
{"key":"main1","value":320},
{"key":"main2","value":240},
{"key":"front1","value":220},
{"key":"main1","value":300},
{"key":"main2","value":240},
{"key":"front1","value":120},
{"key":"front5","value":120}
];
for (i in test) {
element = test[i];
if (!result[element.key]) {
result[element.key]=[element.value];
} else {
result[element.key].push(element.value);
}
}
demo -> http://jsfiddle.net/e8afaak8/

davidkonrad
- 83,997
- 17
- 205
- 265
-
1Don't suggest bad practice. _`for..in` should not be used to iterate over an `Array` where index order is important_ ([ref.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)) – hindmost Mar 11 '15 at 14:41
-
1@hindmost, yes - that would have been a very bad idea **if** OP had given the expression that index order is important. – davidkonrad Mar 11 '15 at 14:50
-
@davidkonrad I meant you shouldn't suggest to use such bad practice (especially for beginners). The problem is not only in index order. T.J. Crowder has pretty detailed [explanation](http://stackoverflow.com/a/9329476/2118955) of why you shouldn't use `for..in` with arrays – hindmost Mar 11 '15 at 15:03