I have the following object, and I want to iterate and check the value of each object i.e. requestArr.st.value
and if there is a value, then return the expr value.
var x = 12345
var y
const requestArr = {
oj: {
"value": x,
"expr": "testX"
},
st: {
"value": y,
"expr": "testY"
},
};
console.log(requestArr.oj.value)
console.log(requestArr.st.value)
for (const [index, key] of Object.keys(requestArr).entries()) {
console.log(key)
}
Currently I can get the object index console.log(key)
how do I navigate to test if there is a value and then return the expr?
update
I am still getting the expression for undefined value, I only want to return the expr for objects that contain a value in the value node.
for (const [index, key] of Object.keys(requestArr).entries()) {
if (requestArr[key].value !== '' || requestArr[key].value !== undefined) {
console.log(requestArr[key].value)
}
}
6
Answers
You can iterate though object keys using for…in loop and inside loop check if requestArr[key].value exist then perform operation or store it in some array like this
Useinng Array.entries() method, you can use Array.forEach or Array.map as well,
You can access the value of any key inside the Array by using the square brackets as such:
Using the key you have in the for loop you can test if the value is undefined by using:
and then outputting the value if its not undefined as below:
Below I have added this to your code:
I’d go with
Object.entries
to access both key and value:You can filter the
Object.values
usingArray.filter
method:You can then add
Array.forEach
method anNd do whatever you want to do with theentry
:ES5
If you use ES5, as you updated your question, you need to loop over the object keys and map them to the object values like:
Why do you have to invoke for
.entries()
? you do not even use theindex
.This is much simpler and direct to the point in my opinion. And should solve your problem:
Instead of
replace it with
You are still getting the undefined value because you are using an
||
operator in yourif
statement. This should be using the&&
,You can further simplify this condition with
if (requestArr[key].value)
TLDR:
Replace your
for
loop with this: