首页
Preview

通过使用map()方法从多维数组中提取特定值来创建新数组

const myFavList = [
  { id: 23, name: "moketaro", favs :[ { fruits: "Apple" }, { hoby: "reading" } ] },
  { id: 11, name: "mokeko", favs :[ { fruits: "lemon" } ] },
  { id: 65, name: "mokemasa", favs :[ { fruits: "orange" }, { hoby: "birdwatching" } ] },
  { id: 190, name: "mokena", favs :[ { fruits: "kiwi" }, { hoby: "travel" } ] },
]

let resFiltered = myFavList.map(({name, favs}) => ({
  name: name,
  fruits: favs.find(fav => fav.fruits)?.fruits
}));

console.log(resFiltered);

输出:

[{
  fruits: "Apple",
  name: "moketaro"
}, {
  fruits: "lemon",
  name: "mokeko"
}, {
  fruits: "orange",
  name: "mokemasa"
}, {
  fruits: "kiwi",
  name: "mokena"
}]

使用的语法

  • 映射()方法
  • 解构
  • 箭头函数
  • 可选的链接运算符 (?.)

版权声明:本文内容由TeHub注册用户自发贡献,版权归原作者所有,TeHub社区不拥有其著作权,亦不承担相应法律责任。 如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

点赞(0)
收藏(0)
秋风
全栈工程师

评论(0)

添加评论