• js 操作对象的小技巧


    来源:https://www.w3cplus.com/javascript/javascript-tips.html

    1、使用...运算符合并对象或数组中的对象

    同样使用ES的...运算符可以替代人工操作,合并对象或者合并数组中的对象。

    // 合并对象 
    const obj1 = { name: '大漠', url: 'w3cplus.com' } 
    const obj2 = { name: 'airen', age: 30 } 
    const mergingObj = {...obj1, ...obj2} 
    > Result: {name: "airen", url: "w3cplus.com", age: 30}
     // 合并数组中的对象 
    const array = [ 
    { name: '大漠', email: 'w3cplus@gmail.com' },
     { name: 'Airen', email: 'airen@gmail.com' } 
    ]
     const result = array.reduce((accumulator, item) => { 
    return { ...accumulator, [item.name]: item.email } 
    }, {}) 
    > Result: {大漠: "w3cplus@gmail.com", Airen: "airen@gmail.com"}

    2、有条件的添加对象属性

    不再需要根据一个条件创建两个不同的对象,以使它具有特定的属性。为此,使用...操作符是最简单的。

    const getUser = (emailIncluded) => { 
    return { 
    name: '大漠', blog: 'w3cplus', ...emailIncluded && {email: 'w3cplus@hotmail.com'}
     } 
    } 
    const user = getUser(true)
     console.log(user) 
    > Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"} 
    const userWithoutEmail = getUser(false) 
    console.log(userWithoutEmail) 
    > Result: {name: "大漠", blog: "w3cplus"}

     

     

  • 相关阅读:
    使用Speex中的AEC模块,提高声音质量(转)
    音频编解码speex库的使用方法
    VC 多线程编程(转)
    并口、串口、COM口区别
    用GDB调试程序
    [转]PCM文件格式
    PreTranslateMessage作用和使用方法
    音频编解码标准
    VS2010 运行速度加快方法(转)
    ON_COMMAND ON_MESSAGE ON_NOTIFY区别与联系
  • 原文地址:https://www.cnblogs.com/arealy/p/11175886.html
Copyright © 2020-2023  润新知