首页 > 解决方案 > 向数组添加 ID

问题描述

我尝试向排序输出中的对象添加id属性,但我所做的一切都不起作用。有什么我应该做的吗?

我的代码如下:

var arr = [{ one: 2 }, 
           { two: 3 }, 
           { three: 4 },
           { four: 1 }];
const arr1 = arr.reduce((a,b) => ({...a,...b}), {}) 
var sorting = Object.entries(arr1).sort((a, b) => b[1] - a[1]);
console.log(sorting);

预期结果:

var arr1 = [{ name: "three", value: 4, id: 1 }, 
            { name: "two", value: 3, id: 2 },
            { name: "one", value: 2, id: 3 },
            { name: "four", value: 1, id: 4 }];

标签: javascripthtmlalgorithm

解决方案


/*If i console.log(sorting) I have  
[['three', 4 ], ['two', 3 ], ['one', 2 ], ['four', 1 ],]
  Without Ids but i want something like the expected result below*/

/*  Expected Result 
[['three', 4 id = 1], ['two', 3 id = 2], ['one', 2 id = 3], ['four', 1 id = 4],]
  */

UPD,对不起,第一次没弄好

var empty = [];

var arr = [{
  one: 2
}, {
  two: 3
}, {
  three: 4
},{
  four: 1
}];
const arr1 = arr.reduce((a,b) => ({...a,...b}), {}) 
const sorting = Object.entries(arr1).sort((a, b) => b[1] - a[1]);
// Add indexes starting from 1
const indexed = sorting.map((a,b) => a.push({ "id": b+1 }));

console.log(sorting);


推荐阅读