将对象数组从数组转换为对象属性 [英] convert array of objects into object of objects properties from array

查看:115
本文介绍了将对象数组从数组转换为对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将对象数组从该数组转换为对象属性的对象。

I need to convert an array of objects into an object of objects properties from the array.

这里是对象数组

const array = [
 {
  book:5,
  car: 6,
  pc: 7
 },
 {
  headphone: 9,
  keyboard: 10
 },
];

我需要将其转换为

const obj = {
 book:5,
 car: 6,
 pc: 7,
 headphone: 9,
 keyboard: 10
};

我尝试了很多方法,但无法获得最终结果。预先感谢

I tried many ways but can't achieve the final result. Thanks in advance

推荐答案

您可以将数组作为参数传播(扩展... ) = https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign rel = noreferrer> Object.assign ,它返回单个对象。

You could spread the array as parameters (spread syntax ...) for Object.assign, which returns a single object.

const
    array = [{ book: 5, car: 6, pc: 7 }, { headphone: 9, keyboard: 10 }],
    object = Object.assign({}, ...array);
    
console.log(object);

这篇关于将对象数组从数组转换为对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆