首页 > 解决方案 > Javascript - 如何将数组中对象的第一个元素分配为另一个数组的键

问题描述

基本上我有一个数组:

我填写了一个 SQL 查询。这使得数组如下:


我想创建另一个数组,其中数组对象的键是组织内对象的第一个元素,因此它们将是 id1、id2 等。

我认为输出应该是这样的:

newArray = [id1: {name1, type2}, id2: {name2, type2}]

标签: javascriptarraysobject

解决方案


试试那个

     const a = [
        { id: 1, name: "peter", city: "New City" },
        { id: 2, name: "alex", city: "New City" },
        { id: 3, name: "michael", city: "New City" }
      ];

      const b = a.map(item => {
        const { id, ...others } = item;

        return { id: { ...others } };
      });

      console.log(b);

推荐阅读