使用 ES2015 处理数组

栏目: JavaScript · 发布时间: 6年前

内容简介:取出数组所有元素中某个将增删所有元素中的

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

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

查看所有标签

猜你喜欢:

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

热搜:搜索排名营销大揭秘

热搜:搜索排名营销大揭秘

【美】肖恩·布拉德利 / 中国人民大学出版社有限公司 / 2018-7-30 / CNY 55.00

首部大数据在我国政府管理场景中的应用实践案例读本,全面展示我国电子政务与数字化建设的成果,深度理解实施国家大数据战略的重要意义。 本书作者作为国内最早从事大数据应用研究的实践者之一,亲历了中国大数据的发展历程、主要事件、应用案例以及行业变化。 在本书中,作者将其所亲历的大数据发展历程进行了阐述,从大数据的基本概念、特点到实践解读,通俗易懂,给我们的实际工作提供了重要参考。作者将帮助读者......一起来看看 《热搜:搜索排名营销大揭秘》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试