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

 

 

 

posted @ 2019-07-12 14:27  拈花醉  阅读(2807)  评论(1编辑  收藏  举报