I have an array and would like to convert it to another structure.
My array:
["DZ|47", "DZ|48", "DZ|53", "DZ|57", "AR|202", "AR|206", "AR|213", "BY|484", "BY|485", "BY|487"]
And I would like to convert this into:
{"DZ":[47,48,53,57],"AR":[202,206,213],"BY":[484,485,487]}
I'm started to write the code, but...what next?
$.each(arr, function( index, value ) {
var idx = value.split('|');
//arr2[idx[0]] = arr3;
});
Thanks!
R3tep
12.9k10 gold badges53 silver badges77 bronze badges
asked Apr 1, 2015 at 7:30
XTRUST.ORG
3,4024 gold badges37 silver badges63 bronze badges
2 Answers 2
var result = {};
$.each(arr, function( index, value ) {
var idx = value.split('|');
if(!result[idx[0]]){
result[idx[0]] = [];
}
result[idx[0]].push(idx[1]);
});
Sign up to request clarification or add additional context in comments.
Comments
You can use Array.prototype.reduce method:
var data = ["DZ|47", "DZ|48", "DZ|53", "DZ|57", "AR|202", "AR|206", "AR|213", "BY|484", "BY|485", "BY|487"];
var result = data.reduce(function(prev, curr) {
var split = curr.split('|');
if (!prev[split[0]]) prev[split[0]] = [];
prev[split[0]].push(split[1]);
return prev;
}, {});
alert(JSON.stringify(result));
answered Apr 1, 2015 at 7:35
dfsq
193k26 gold badges244 silver badges261 bronze badges
Comments
lang-js