Reputation: 944
var response = transport.responseJSON || transport.responseText.evalJSON(true) || {};
// console.log(response)
// log results
account: []
agreements: []
billing: []
order: {error: 1, message: "Ingenico ePayments Payment failed", goto_section: "payment"}
payment: []
shipping: []
alert(response.account.message);
Depending on what message comes back from the response is there a way I can loop through the AJAX response and display the associated message rather than hardcoding the value like in the above (response.account.message) as sometimes for example the error will come from a different section like:
account: {error: 1, message: "An account already exists for this email address."}
Upvotes: 0
Views: 39
Reputation: 7346
You probable want to use the for..in loop, which goes through the keys of an object or other iteratable. More about for..in
var response = JSON.parse('{"account":{"error":1,"message":"your message"},"agreements":{"error":1,"message":"your second message"}}');
for (let type in response) {
if (response[type].error) {
var msg = response[type].message;
console.log(type + " : '" + msg + "'");
}
}
Upvotes: 1
Reputation: 1241
You can do this using a combination of Object.values
and Array.reduce
:
Object.values(response).reduce((acc, val) => {
if (typeof val === 'Object' && typeof val.message !== 'undefined') {
return val
} else {
return acc
}
})
Or if you want an array of all messages:
Object.values(response)
.filter(val => typeof val === 'Object')
.filter(val => val.error === 1)
.filter(val => typeof val.message !== 'undefined')
.map(val => val.message);
Upvotes: 1