从对象数组构建对象的最佳方法(Most performant way to build object from array of objects)

编程入门 行业动态 更新时间:2024-10-09 18:25:58
对象数组构建对象的最佳方法(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);

                    
                     
          

更多推荐

本文发布于:2023-08-02 09:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   数组   方法   performant   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!