I have an array of objects as below :
var jsonResponse = [
{"Geo":"Asia",
"Country":["China","Japan","India"],
"contact": "[email protected]"},
{"Geo":"Europe",
"Country":["Austria","Germany","UK"],
"contact": "[email protected]"},
{"Geo":"Africa",
"Country":"Egypt",
"contact": "[email protected]"},
... ];
I want to loop through each object by key, merge all unique values and store in a new array of objects.
The result should be as below :
var newjsonResponse = [
{"Geo":"world wide",
"Country":["China","Japan","India","Austria","Germany","UK","Egypt"],
"contact": ["[email protected]","[email protected]"]
}];
Here is my code. Any suggestions please what am I doing wrong ? Thank you very much.
var jsonResponse = [
{"Geo":"Asia",
"Country":["China","Japan","India"],
"contact": "[email protected]"},
{"Geo":"Europe",
"Country":["Austria","Germany","UK"],
"contact": "[email protected]"},
{"Geo":"Africa",
"Country":"Egypt",
"contact": "[email protected]"}];
var arrGeo = [];
var arrCountry = [];
var arrcontact = [];
var newjsonResponse = [{"Geo":"world wide"}];
$.each(jsonResponse, function(key,value) {
arrCountry.push(value["Country"]);
arrcontact.push(value["contact"]);
newjsonResponse["Country"].push(arrCountry);
newjsonResponse["Contact"].push(arrcontact);
});
console.log(newjsonResponse);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>