使用 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 }]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 在项目实践中用更优雅的方式处理数组问题
- js处理大数据数组循环的一些性能优化
- 深入解析 C++ 中的字符数组和处理字符串的方法
- 关于ES6数组方法在低版本浏览器处理
- C语言指针数组和数组指针
- 数组 – 如何在Swift中将数组拆分成两半?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。