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

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

查看所有标签

猜你喜欢:

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

Head First JavaScript Programming

Head First JavaScript Programming

Eric T. Freeman、Elisabeth Robson / O'Reilly Media / 2014-4-10 / USD 49.99

This brain-friendly guide teaches you everything from JavaScript language fundamentals to advanced topics, including objects, functions, and the browser’s document object model. You won’t just be read......一起来看看 《Head First JavaScript Programming》 这本书的介绍吧!

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

在线压缩/解压 HTML 代码

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

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具