比如我有一个数组
let arry = [
{"selected":true,"name":"Tony"},
{"selected":false,"name":"Lily"},
{"selected":true,"name":"Liyang"}];
JS中我使用for循环如何获取仅selected为true的值?
for(var i=0;i<arry.length;i++){
if(arry[i].selected=true){
console.log(arry[i].name)
}
}
以上的for中国,打印出来的依然是3个字符串。而我仅需要["Tony","Liyang"]这样的格式,我该如何才能获取?
之前试过使用push添加到一个空数组中,但是push中每for一次就仅push当前for到的值,而并不会将所有值添加到一个数组中去!
求大神帮帮忙!
给我你的怀抱2017-06-26 10:56:04
用 filter
和 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);