Home  >  Q&A  >  body text

How to reorganize an array from the value of for loop in JavaScript and angular2

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!

滿天的星座滿天的星座2672 days ago685

reply all(5)I'll reply

  • typecho

    typecho2017-06-26 10:56:04

    if(arry[i].selected=true)

    This is wrong, it is written as assignment.

    reply
    0
  • PHP中文网

    PHP中文网2017-06-26 10:56:04

    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.

    reply
    0
  • typecho

    typecho2017-06-26 10:56:04

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

    reply
    0
  • typecho

    typecho2017-06-26 10:56:04

    var newArr = []
    arry.forEach(function(value){if(value.selected) newArr.push(value.name)})

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-26 10:56:04

    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);

    reply
    0
  • Cancelreply