小编给大家分享一下JavaScript如何使用展开运算符合并对象和对象数组,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
使用展开运算符合并对象和对象数组
对象合并是很常见的事情,我们可以使用新的ES6特性来更好,更简洁的处理合并的过程。
// merging objects const product = { name: 'Milk', packaging: 'Plastic', price: '5$' } const manufacturer = { name: 'Company Name', address: 'The Company Address' } const productManufacturer = { ...product, ...manufacturer }; console.log(productManufacturer); // outputs { name: "Company Name", packaging: "Plastic", price: "5$", address: "The Company Address" } // merging an array of objects into one const cities = [ { name: 'Paris', visited: 'no' }, { name: 'Lyon', visited: 'no' }, { name: 'Marseille', visited: 'yes' }, { name: 'Rome', visited: 'yes' }, { name: 'Milan', visited: 'no' }, { name: 'Palermo', visited: 'yes' }, { name: 'Genoa', visited: 'yes' }, { name: 'Berlin', visited: 'no' }, { name: 'Hamburg', visited: 'yes' }, { name: 'New York', visited: 'yes' } ]; const result = cities.reduce((accumulator, item) => { return { ...accumulator, [item.name]: item.visited } }, {}); console.log(result); /* outputs Berlin: "no" Genoa: "yes" Hamburg: "yes" Lyon: "no" Marseille: "yes" Milan: "no" New York: "yes" Palermo: "yes" Paris: "no" Rome: "yes" */
以上是“JavaScript如何使用展开运算符合并对象和对象数组”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。