繁体   English   中英

Javascript - 如何将数组中对象的第一个元素分配为另一个数组的键

[英]Javascript - How to assign the first element of an object in array to be the key of another array

基本上我有一个数组:

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


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

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

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

试试那个

     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);

这是 Petia 解决方案的修改版本。 @Petia:我希望你不介意我复制你的样本数据。

 const a = [ { id: 11, name: "peter", city: "New City" }, { id: 12, name: "Alex", city: "Another City" }, { id: 31, name: "Michael", city: "Third City" } ], b = {}; a.forEach(obj=>{b[obj.id]=obj}); console.log(b);

在此解决方案中,对象的结果对象仍将id属性作为列出对象的一部分。 如果需要,可以通过以下表达式轻松删除这些id属性:

Object.values(b).forEach(obj=>{delete obj.id});

目前还不清楚您在问什么,但假设您的对象包含变量而不是字符串,这可能会有所帮助。

 id1=1; name1='bob' type1='ajax' id2=2; name2='sid' type2='comet' org = [ {id1, name1,type1}, {id2, name2, type2}] neworg={} for(i=0;i<org.length;i++){ id = Object.values(org[i])[0] arr=new Array(); for (j=1;j<Object.keys(org[i]).length;j++){ arr.push(Object.values(org[i])[j]) } neworg[id]={arr} } console.log(neworg)

可以使用map()函数和spread ...运算符:

const result = a.map(s => ({[s.id]:{...s}}));

和例子:

 const a = [ { id: 10, name: "Science", Type: "Type 1" }, { id: 20, name: "Management", Type: "Type 2" }, { id: 30, name: "Sport", Type: "Type 3" } ]; const result = a.map(s => ({[s.id]:{...s}})); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM