gpt4 book ai didi

javascript - 返回对象数组中名称(许多名称)的最后一次出现

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:11:12 27 4
gpt4 key购买 nike

给定以下数据源:

[
{
"Username" : "Patrick",
"Time" : "08:01:32",
"Status" : "log in"
},
{
"Username" : "Patrick",
"Time" : "08:34:31",
"Status" : "idle"
},
{
"Username" : "Patrick",
"Time" : "08:52:10",
"Status" : "meeting"
},
{
"Username" : "Patrick",
"Time" : "10:07:52",
"Status" : "daily tasks"
},
{
"Username" : "Patrick",
"Time" : "12:00:11",
"Status" : "lunch"
},
{
"Username" : "Mark",
"Time" : "07:40:32",
"Status" : "log in"
},
{
"Username" : "Mark",
"Time" : "08:54:31",
"Status" : "meeting"
},
{
"Username" : "Mark",
"Time" : "09:52:10",
"Status" : "idle"
},
{
"Username" : "Mark",
"Time" : "10:07:52",
"Status" : "daily tasks"
},
{
"Username" : "Mark",
"Time" : "12:30:11",
"Status" : "lunch"
}
]

如何以简单的方式获取此数组中每个名称的最后一次出现?我在考虑过滤器功能,但是我不确定如何进行。任何支持或提示将不胜感激。

预期的结果应该如下:

[
{
"Username" : "Patrick",
"Time" : "12:00:11",
"Status" : "lunch"
},
{
"Username" : "Mark",
"Time" : "12:30:11",
"Status" : "lunch"
}
]

最佳答案

使用 ES6,您可以将数组缩减为映射,然后将值散布回数组:

const data = [{"Username":"Patrick","Time":"08:01:32","Status":"log in"},{"Username":"Patrick","Time":"08:34:31","Status":"idle"},{"Username":"Patrick","Time":"08:52:10","Status":"meeting"},{"Username":"Patrick","Time":"10:07:52","Status":"daily tasks"},{"Username":"Patrick","Time":"12:00:11","Status":"lunch"},{"Username":"Mark","Time":"07:40:32","Status":"log in"},{"Username":"Mark","Time":"08:54:31","Status":"meeting"},{"Username":"Mark","Time":"09:52:10","Status":"idle"},{"Username":"Mark","Time":"10:07:52","Status":"daily tasks"},{"Username":"Mark","Time":"12:30:11","Status":"lunch"}];


const result = [...data.reduce((m, o) => m.set(o.Username, o), new Map()).values()];

console.log(result);

在 ES5 中,您可以将数组缩减为包含唯一项的对象,然后使用 Object#keys 将该对象映射回数组:

var data = [{"Username":"Patrick","Time":"08:01:32","Status":"log in"},{"Username":"Patrick","Time":"08:34:31","Status":"idle"},{"Username":"Patrick","Time":"08:52:10","Status":"meeting"},{"Username":"Patrick","Time":"10:07:52","Status":"daily tasks"},{"Username":"Patrick","Time":"12:00:11","Status":"lunch"},{"Username":"Mark","Time":"07:40:32","Status":"log in"},{"Username":"Mark","Time":"08:54:31","Status":"meeting"},{"Username":"Mark","Time":"09:52:10","Status":"idle"},{"Username":"Mark","Time":"10:07:52","Status":"daily tasks"},{"Username":"Mark","Time":"12:30:11","Status":"lunch"}];

var uniques = data.reduce(function(m, o) {
m[o.Username] = o;

return m;
}, Object.create(null));

var result = Object.keys(uniques).map(function(key) {
return uniques[key];
});

console.log(result);

关于javascript - 返回对象数组中名称(许多名称)的最后一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46421613/

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