For example, I have an array
let arry = [
{"selected":true,"name":"Tony"},
{"selected":false,"name":"Lily"},
{"selected":true,"name":"Liyang"}];
How do I use a for loop in JS to get only the values that are selected to be true?
for(var i=0;i<arry.length;i++){
if(arry[i].selected=true){
console.log(arry[i].name)
}
}
The above for China still prints out 3 strings. And I only need the format ["Tony","Liyang"], how can I get it?
I have tried using push to add to an empty array before, but every for in the push only pushes the value currently reached by for, and does not add all the values to an array!
Please help me!
This is wrong, it is written as assignment.
One = is assignment, and two = is comparison. Please be more careful when writing next time. Sometimes the logic is fine, but it just doesn’t work. Then there may be a syntax problem somewhere.
Just use
arry[i].selected
to determine. Why do we need to determine whether the values are equal?It’s so convenient to use
filter
andmap