August 16, 2012

Json Format Getting Multiples ID

There is quite simple and easy way to get multiple ID's from json return string using javascript. If my desire output result will be as below

[{"RelationLevel1Id":0,"ParentLevelId":0,"ChildLevelId":5,"HierarchyLevel1":null,"HierarchyLevel2":null},{"RelationLevel1Id":0,"ParentLevelId":0,"ChildLevelId":13,"HierarchyLevel1":null,"HierarchyLevel2":null},{"RelationLevel1Id":0,"ParentLevelId":0,"ChildLevelId":14,"HierarchyLevel1":null,"HierarchyLevel2":null}]

If i want to retrieve ChildLevelId as 5,13,14 then use below code. Modify it according to your need.

USING JAVASCRIPT

var myArr = [{ "RelationLevel1Id": 0, "ParentLevelId": 0, "ChildLevelId": 5, "HierarchyLevel1": null, "HierarchyLevel2": null }, { "RelationLevel1Id": 0, "ParentLevelId": 0, "ChildLevelId": 13, "HierarchyLevel1": null, "HierarchyLevel2": null }, { "RelationLevel1Id": 0, "ParentLevelId": 0, "ChildLevelId": 14, "HierarchyLevel1": null, "HierarchyLevel2": null}];

var ChildArry = [];
for (var i = 0; i < myArr.length; i++) {
var Child = {};
Child.ChildLevelId = myArr[i].ChildLevelId;
ChildArry[i] = Child;
}

var finalOutput = JSON.stringify(ChildArry)


USING jQUERY

var data = [{ "RelationLevel1Id": 0, "ParentLevelId": 0, "ChildLevelId": 5, "HierarchyLevel1": null, "HierarchyLevel2": null },
{ "RelationLevel1Id": 0, "ParentLevelId": 0, "ChildLevelId": 13, "HierarchyLevel1": null, "HierarchyLevel2": null },
{ "RelationLevel1Id": 0, "ParentLevelId": 0, "ChildLevelId": 14, "HierarchyLevel1": null, "HierarchyLevel2": null}];
var childIDonly = $.map(data, function(a, i) {
return a.ChildLevelId;
})
var ids = JSON.stringify(childIDonly);