Iterate And Map Json In Array Using Javascript
I'am struck here that mapping a JSON in a array. Here I have mentioned JSON array. [ { '_id':{ '$oid':'51d84a1e07121c7f442a6e76' }, '_type':[ 'App_Model_Playlist_Content_Heading',
Solution 1:
You should iterate over JSON array, and create a new entry either if you faces an App_Model_Playlist_Content_Heading
or the currentObj is null, thus, it has no heading, like this
var array = [],
currentObj,
pushNew = function(header, narrative, resourceId) {
var newObj = {
header: header || '',
narrative: narrative || '',
resource_id: resourceId? [resourceId] : []
};
array.push(newObj);
return newObj;
}
;
for(var i=0; i < aa.length; i++){
// Starting of a new entry
if(aa[i]._type[0]=='App_Model_Playlist_Content_Heading'){
currentObj = pushNew(aa[i].text);
}
if(aa[i]._type[0]=='App_Model_Playlist_Content_Narrative'){
if(!currentObj) {
currentObj = pushNew(null, aa[i].text);
} else {
currentObj.narrative = aa[i].text;
}
}
if(aa[i]._type[0]=='App_Model_Playlist_Content_Resource'){
if(typeof aa[i].resource !== 'undefined' && aa[i].resource != null && aa[i].resource !==''){
if(!currentObj) {
currentObj = pushNew(null, null, aa[i].resource.$id.$oid);
} else {
currentObj.resource_id.push(aa[i].resource.$id.$oid);
}
}
}
}
console.log(JSON.stringify(array));
Post a Comment for "Iterate And Map Json In Array Using Javascript"