topcat3 topcat3 - 3 months ago 6
JSON Question

jQuery return all items from JSON

function loadDoc(url) {
$.ajax({
url: 'mytestjson',
dataType: 'json',
cache: false
}).success(function (result) {
console.log(result);
//var txt = result.newBranches[0].newNonBranchLocation;
$.each(result.newBranches, function(index, txt)
{
// change this to FALSE when ready
if (newNonBranchLocation.indexOf('TRUE') > -1) {
$('#btbumpin').hide();
}
else {
$('#btbumpin').show();
}
});
})
}

{
"errorNode": {
"errorCode": 0,
"errorMsg": "",
"errorSev": ""
},
"newBranches": [{
"cn": "11111101",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111102",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111103",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111181",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}]


}

I have the above jquery and JSON. I want to return all the values inside newBranches but it only return the values from the first "cn": "11111101",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"

Ideally it will return a string like 11111101TRUE11111111111102TRUE111111 and so on

Answer

Declare a variable outside the loop, for ex

var output = '';

Inside the loop you can just append all the values you need to the variable.

output + = txt.cn + txt.newNonBranchLocation + txt.newBranchNumber;

After the loop is completed, you can use this variable which will contain the appended string.

Comments