使用 ES2015 处理数组
栏目: JavaScript · 发布时间: 7年前
内容简介:取出数组所有元素中某个将增删所有元素中的
Array.map()
取出数组所有元素中某个 字段
const channels = [
{"id": 4, "title": "文化", "platform": "app", "type": "channel", "ordering": 4},
{"id": 1, "title": "推荐", "platform": "app", "type": "channel", "ordering": 1},
{"id": 7, "title": "人物", "platform": "app", "type": "channel", "ordering": 5}
]
const mapped = channels.map(item => item.title)
console.log(mapped)
> Array ["文化", "推荐", "人物"]
将 callback
函数返回值组成一个数组,这里 ES6 箭头写法省略了 return
增删所有元素中的 字段
const channels = [
{"id": 4, "title": "文化", "platform": "app", "type": "channel", "ordering": 4},
{"id": 1, "title": "推荐", "platform": "app", "type": "channel", "ordering": 1},
{"id": 7, "title": "人物", "platform": "app", "type": "channel", "ordering": 5}
]
const mapped = channels.map(item => {
const { platform, ordering, ...rest } = item
return {
...rest,
author: '',
link: `//www.adc.com/channel/${item.id}`
}
})
console.log(mapped)
> Array [
Object { id: 4, title: "文化", type: "channel", author: "", link: "//www.adc.com/channel/4" },
Object { id: 1, title: "推荐", type: "channel", author: "", link: "//www.adc.com/channel/1" },
Object { id: 7, title: "人物", type: "channel", author: "", link: "//www.adc.com/channel/7" }
]
配合扩展运算符、 rest
参数、对象解构将需要的字段重新组合成新的数组。
Array.find()
找到数组元素中某 符合项
const status = [
{ id: "3", name: "草稿" },
{ id: "0", name: "未发布" },
{ id: "1", name: "已发布" },
{ id: "2", name: "等待发布" },
{ id: "4", name: "已撤稿" },
]
const item_status = 1
status.find(option => option.id == item_status)
> Object { id: "1", name: "已发布" }
Array.filter()
取出数组元素中 适合的元素
const channels = [
{ "id": 4, "title": "文化", "platform": "pc", "type": "channel", "ordering": 4},
{ "id": 1, "title": "推荐", "platform": "app", "type": "channel", "ordering": 1},
{ "id": 7, "title": "人物", "platform": "app", "type": "channel", "ordering": 5}
]
channels.filter(item => {
return item.platform === 'pc' && item.type === 'channel'
})
> Array [Object { id: 4, title: "文化", platform: "pc", type: "channel", ordering: 4 }]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Learning Web App Development
Semmy Purewal / O'Reilly Media / 2014-3-3 / USD 29.99
Grasp the fundamentals of web application development by building a simple database-backed app from scratch, using HTML, JavaScript, and other open source tools. Through hands-on tutorials, this pract......一起来看看 《Learning Web App Development》 这本书的介绍吧!