Reputation: 1273
I am getting back this JSON object from an Ajax call it will be larger than one object but starting with just one record for now.
[{
"SCENARIOID":"b9711a68-fb67-4b5c-bf79-a8a7a9a27df3",
"USERID":"35be8bbb-99dc-44bc-9d84-9bcc937d79d6",
"DateConfirmed":"\/Date(1434603186197)\/",
"IsCorrect":true
}]
I have a <div id=test> </div>
in my code and I am wanting to populate an unordered list with the USERID
from the JSON object but only when IsCorrect == true
My current try is
$('#test').append('<ul id="fullCorrectByList"><ul/>');
$.each(response, function (key, data) {
console.log(key);
console.log(data);
$.each(data, function (index, data) {
if (index == 'IsCorrect' && data == true) {
console.log('IsCorrect and True');
//how do I console.log USERID for this json record?
}
console.log(index + ' : ' + data)
})
})
console.log(response);
Upvotes: 0
Views: 88
Reputation: 388316
There is no need of the second loop, if the properties you want to deal with are constant.
$('#test').append('<ul id="fullCorrectByList"><ul/>');
$.each(response, function (index, record) {
console.log(index);
console.log(record);
if (record.IsCorrect) {
console.log('correct', record.USERID)
}
})
console.log(response);
If you want to make your code work, then just rename the variables uniquely to access the closure values
var response = [{
"SCENARIOID": "b9711a68-fb67-4b5c-bf79-a8a7a9a27df3",
"USERID": "35be8bbb-99dc-44bc-9d84-9bcc937d79d6",
"DateConfirmed": "\/Date(1434603186197)\/",
"IsCorrect": true
}];
$('#test').append('<ul id="fullCorrectByList"><ul/>');
$.each(response, function(index, record) {
console.log(index);
console.log(record);
$.each(record, function(key, value) {
if (key == 'IsCorrect' && value == true) {
console.log('IsCorrect and True');
//how do I console.log USERID for this json record?
console.log('USERID: '+record.USERID)
}
console.log(key + ' : ' + value)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 1