Reputation:
I have a array of events and i want to make relation between these array's object. array:
[{
'area': 'punjab',
'site': 'lahore',
'link': 'http: //lahore.com'
}, {
'area': 'punjab',
'site': 'sargodha',
'link': 'http: //sargodha.com'
}, {
'area': 'punjab',
'site': 'multan',
'link': 'http: //multan.com'
} {
'area': 'sindh',
'site': 'karachi',
'link': 'http: //karachi.com'
}]
Know i want to make the relation like
{
"area": "punjab",
"site": [
{
"name": "lahore",
"link": [
{
"name": "http://sargodha.com",
}
]
},
{
"name": "sargodha",
"link": [
{
"name": "http://sargodha.com",
}
]
}
]
},
{
"area": "sindh",
"site": [
{
"name": "karachi",
"link": [
{
"name": "http://karachi.com",
}
]
}
}
here is my code which i wrote:
function isinarrayfilters(matchingObject, targetArray, key) {
var existindex = -1;
$.each(targetArray, function(index, array) {
if (array.key == matchingObject.key) {
//Object exist in array
existindex = index;
}
});
return existindex;
}
generatedRelationArray = [];
$.each(alertsJson, function(index, alertJson) {
inarrayindex = isinarrayfilters(alertJson.area, relationArray,'area');
if (inarrayindex == -1) {
key = alertJson.site
generatedsites = {
"area": alertJson.area,
"site": []
}
relationArray.push(generatedsites);
}
});
Know anyone guide me how i append the site into the related area.
Upvotes: 4
Views: 92
Reputation: 21742
You can use query-js to accomplish this
Assuming your original array is stored in data
var res = data.groupBy(function(e){ return e.area; });
That would create a slightly different structure:
{
"punjab" : [{
'area': 'punjab',
'site': 'lahore',
'link': 'http: //lahore.com'
}, {
'area': 'punjab',
'site': 'sargodha',
'link': 'http: //sargodha.com'
}, {
'area': 'punjab',
'site': 'multan',
'link': 'http: //multan.com'
}],
"sindh": [...]
}
If you need that explicit structure then you can do this instead
var res = data.groupBy(function(e){ return e.area; })
.each(function(e){
return {
area : e.key,
site : e.value.select(function(e){
return {
name : e.site,
linkm : [e.link]
};
});
});
I've created a post that's supposed to be explanatory of what query-js is and how to use it
Upvotes: 0
Reputation: 9813
A Format preserved answer:
var generate = function(list) {
var resultList = [];
var tmpStoreRef = {};
$.each(list, function(id, item) {
var area = item.area
,site = item.site
,link = item.link;
if (typeof tmpStoreRef[area] === 'undefined') {
tmpStoreRef[area] = {
area: area,
site: []
}
resultList.push(tmpStoreRef[area]);
}
tmpStoreRef[area].site.push({
name: site,
link: link
});
});
return resultList;
};
Upvotes: 2