gpt4 book ai didi

javascript - 处理对象操作数组

转载 作者:行者123 更新时间:2023-11-28 11:11:14 25 4
gpt4 key购买 nike

下面我有一个对象数组

var data = [{
"time": "1572024707.4763825",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}, {
"time": "1572024708.3903246",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
}]

如何重组它以删除时间最早的重复 ID

我尝试从数组中提取所有唯一 ID,以便可以循环访问数据数组,但代码开始变得太长。

  data.forEach(item => {

IDs.push(item.id);
});

var unqIDs = [...new Set(IDs)];
console.log(unqIDs);

输出应如下所示

outPutShouldBe = [{
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
},{
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}
]

最佳答案

创建一个将 id 映射到具有该 id 的项目的最早时间的对象:

var keydata = {};
data.forEach(item=>{
var p = keydata[item.id];
if ( !p || p.time>item.time ) {
keydata[item.id] = item;
}});

现在收集该对象中的值:

var newdata = [];
for ( var k in keydata ) {
newdata.push(keydata[k]);
}

或更优雅的(谢谢,@TulioF。):

var newdata = Object.values(keydata)

关于javascript - 处理对象操作数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com