How to reorganize an array from the value of for loop in JavaScript and angular2
滿天的星座
滿天的星座 2017-06-26 10:54:04
0
5
733

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!

滿天的星座
滿天的星座

reply all(5)
typecho
if(arry[i].selected=true)

This is wrong, it is written as assignment.

Ty80

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.

typecho

Just use arry[i].selected to determine. Why do we need to determine whether the values ​​are equal?

typecho
var newArr = []
arry.forEach(function(value){if(value.selected) newArr.push(value.name)})
给我你的怀抱

It’s so convenient to use filter and map

let arry = [
    { "selected": true, "name": "Tony" },
    { "selected": false, "name": "Lily" },
    { "selected": true, "name": "Liyang" }
];

let selected = arry.filter(m => m.selected);

console.log("selected", selected);

let names = selected.map(m => m.name);
console.log("names", names);

// 连起来

let result = arry
    .filter(m => m.selected)
    .map(m => m.name);
console.log("result", result);

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template