javascript - 向数组添加 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 }];
解决方案
/*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);
推荐阅读
- javascript - Ajax/jQuery Django 刷新类元素
- javascript - 如何在highcharts 3d中更改相机角度
- css - 将样式组件与反应和故事书一起使用时字体未加载
- python - 使用 Selenium + Python 3.8 并且无法单击链接,想知道如何处理 onclick?
- c# - Xamarin 表单 ViewModel 与列表中的列表
- python - AttributeError:模块“tensorflow.compat”没有属性“v1”Tensorflow v:1.10.0
- node.js - 未定义必需的,使用电子时,我该如何解决?(已经尝试过节点集成)
- c# - 使用现有方法或重写 - 帮助程序库
- powershell - 在 WebsCount 参数中列出 0 的 SharePoint Online 子网站
- ios - 如何使用我的操作系统版本在 Apple Watch 上安装应用程序?