使用 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 }]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

网络营销

网络营销

拉菲·默罕默德 / 王刊良 / 中国财政经济出版社 / 2004-10 / 65.00元

本书提供了一个将网络营销与传统营销进行整合的分析和设计框架,称之为“市场空间矩阵”,该框架贯穿本书。利用该框架可以对网络营销战略、营销手段等进行系统的分析、设计和评价。 本书还有一条脉络,即客户关系的四个阶段,这一线索是市场空间矩阵的一个维度。在客户关系的框架下对营销手段(产品、价格、渠道、促销、社区、传播、品牌)进行分析和设计,旨在将客户从认知阶段经过探索/扩展阶段快速推进到承诺阶段。 ......一起来看看 《网络营销》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具