-
江户川乱折腾
你只需要filter和map。使用filter你将得到那些selected真正有价值的人。用于将这些对象的值map映射slug到数组中。var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]var newArray = diet.filter(f => f.selected).map(m => m.slug)console.log(newArray)
-
慕桂英4014372
您可以使用方法来过滤选择值为 true 的filter记录。这将返回满足条件的对象数组var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]console.log(diet.filter(e => e.selected))如果只想返回slug属性,可以使用filter和map方法组合var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ] console.log(diet.filter(e => e.selected == true).map(e => e.slug))
-
桃花长相依
Array像这样使用函数filter和的组合map:let diet= [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]let selected=diet.filter(type=>type.selected).map(selectedType=>selectedType.slug)console.log(selected)不幸的是,这需要对数组进行两次迭代,一次过滤掉selected,一次只返回slugreduce您也可以使用这样的方法获得相同的结果let diet= [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]let reduced = diet.reduce((filtered, option)=> { if (option.selected) { filtered.push(option.slug); } return filtered;}, []);console.log(reduced)reduce将是推荐的方法,因为您只在数组上迭代一次
-
德玛西亚99
另一种方式可能是final newList = diet.fold<List>([], (previousValue, e) { if (e["selected"]) { previousValue.add(e["slug"]); } return previousValue; });