根据布尔属性将对象数组减少为字符串数组

我想根据布尔属性将对象数组减少为字符串数组。

我的对象数组如下所示:

diet: [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]

如果所选值为 true,我的理想结果将是一个字符串数组。

["dairy-free", "poultry", "vegetarian"]


凤凰求蛊
浏览 156回答 4
4回答

江户川乱折腾

你只需要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) {&nbsp; &nbsp; &nbsp; if (e["selected"]) {&nbsp; &nbsp; &nbsp; &nbsp; previousValue.add(e["slug"]);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return previousValue;&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript