I have a project that I'm working on using Node.js
and I'm having trouble when I try to iterate through object properties. I'm new to this kind of iteration. I'm used to write data.value
to access a value, but I can't access a value like that, I need to access the value by using iteration in JavaScript.
I have this JSON
data
var data = {
"internal": {
"services": {
"core": "OK",
"comments": "NOK",
"id": "OK"
}
}
}
I need to get the OK
or NOK
values using JavaScript iteration.
I tried this
for (var key of Object.values(data)) {
if (key === 'NOK') {
axios.post(slackWebhookURL, {
text: `Problems found in ${key}`
})
} else axios.post(slackWebhookURL, {
text: 'Everything is working properly.'
})
}
I've tried with Object.keys()
, Object.entries()
, Object.getOwnPropertyName()
but none of them worked, none of them returned OK
or NOK
.
Any kind of help is appreciated.
Use the function entries
as follow:
for (var [key, value] of Object.entries(data.internal.services)) {...}
var data = { "internal": { "services": { "core": "OK", "comments": "NOK", "id": "OK" } } } for (var [key, value] of Object.entries(data.internal.services)) { if (value === 'NOK') { console.log(`Problems found in '${key}'`); } else { console.log(`Everything is working properly in '${key}'`); } }
You need to access the correct property of your object literal. Also, simply use some()
var data = { "internal": { "services": { "core": "OK", "comments": "NOK", "id": "OK" } } }; if (Object.values(data.internal.services).some(e => e === 'NOK')) { axios.post(slackWebhookURL, { text: `Problems found in ${key}` }); } else { axios.post(slackWebhookURL, { text: 'Everything is working properly.' }); }
You use the 'dot' syntax to access the inner properties
console.log('core: ' + data.internal.services.core);
console.log('comments: ' + data.internal.services.comments);
console.log('id: ' + data.internal.services.id);
To iterate you need to loop through the object that contains the properties whose values you want to observe, in this case data.internal.services
.
var data = { "internal": { "services": { "core": "OK", "comments": "NOK", "id": "OK" } } } for (var propName in data.internal.services) { if (data.internal.services[propName] === 'NOK') { console.log(propName + ': NOK') } else { console.log(propName + ': OK') } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.