例如我有一個陣列
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);