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

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM