Reputation: 9476
I have multiple JSON data like
var resultJSON =
'{"l":"1","p":"1","name":"john"},
{"l":"1","p":"2","name":"john1"},
{"l":"1","p":"2","name":"john2"}';
So Now,
I want to generate multidimensional array using jquery
resultJSON.each(function(){
var result = $.parseJSON(resultJSON);
obj[1][1] = array("john");
}
How can I generate multidimensional array and if array has common key append the name?
OUTPUT will be:
obj[1][1] = array("john");
obj[1][2] = array("john1","john2");
Upvotes: 0
Views: 88
Reputation: 28196
var src=[{"l":"1","p":"1","name":"john"},
{"l":"1","p":"2","name":"john1"},
{"l":"1","p":"2","name":"john2"}];
var obj={};
$.each(src,function(i,v){
if (!obj[v.l]) {obj[v.l]={};obj[v.l][v.p]=[v.name]}
else if (!obj[v.l][v.p]) obj[v.l][v.p]=[v.name]
else obj[v.l][v.p].push(v.name);
})
The only jquery element in this is the $.each()
method which you can even replace by the Array method .forEach()
(the order of the anonymous function arguments must be changed then).
Upvotes: 2
Reputation: 6484
Firstly, your JSON is not an array, so you shold add square brackets.
Moreover you should check for each level of your final array, if the value exists and eventually initialize an array and push the name inside it.
var results = $.parseJSON('['+resultJSON+']');
var obj = [];
$.each(results, function(i, res){
var l = res.l, p = res.p;
if(!obj[l]) obj[l] = [];
if(!obj[l][p]) obj[l][p] = [];
obj[l][p].push(res.name)
});
You can find a snippet here:
var resultJSON = '{"l":"1","p":"1","name":"john"}, {"l":"1","p":"2","name":"john1"},{"l":"1","p":"2","name":"john2"}';
var results = $.parseJSON('['+resultJSON+']');
var obj = [];
$.each(results, function(i, res){
var l = res.l, p = res.p;
if(!obj[l]) obj[l] = [];
if(!obj[l][p]) obj[l][p] = [];
obj[l][p].push(res.name)
});
$('#output1').text(JSON.stringify(obj));
$('#output2').text(JSON.stringify(obj[1][2]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<output id="output1"></output>
<br>
<output id="output2"></output>
EDIT
Alternative way:
var obj = {};
$.each(results, function(i, res){
var l = res.l, p = res.p;
if(!obj[l]) obj[l] = {};
if(!obj[l][p]) obj[l][p] = [];
obj[l][p].push(res.name)
});
//output {"1":{"1":["john"],"2":["john1","john2"]}}
Upvotes: 2