从对象数组构建对象的最佳方法(Most performant way to build object from array of objects)
目前,我正在使用以下内容从一组对象构建对象:
var popOverOptions = { defaultOption: true } if (a) { options.push({a: "b"}); } if (c) { options.push({c: "d"}); } // Loop through array of objects for (var i = 0; i < options.length; i++) { // Add objects in array to popoverOptions object for (key in options[i]) { popoverOptions[key] = options[i][key] } }我认为这可以优化,我很好奇是否有更好的方法来编写它,可能使用.reduce(),. forEach()或其他方法。
Currently, I'm building an object from an array of objects with the following:
var popOverOptions = { defaultOption: true } if (a) { options.push({a: "b"}); } if (c) { options.push({c: "d"}); } // Loop through array of objects for (var i = 0; i < options.length; i++) { // Add objects in array to popoverOptions object for (key in options[i]) { popoverOptions[key] = options[i][key] } }I'm thinking this could be optimized and I'm curious if there is a better way to write this, possibly using .reduce(), .forEach() or some other method.
最满意答案
在ECMAScript 6中,您可以使用
Object.assign将属性复制到popOverOptions 扩展运算符以扩展options数组。Object.assign(popOverOptions, ...options);In ECMAScript 6, you can use
Object.assign to copy the properties to popOverOptions The spread operator to expand the options array.Object.assign(popOverOptions, ...options);
更多推荐
发布评论