gpt4 book ai didi

javascript - 根据键值对过滤对象

转载 作者:行者123 更新时间:2023-11-29 23:00:54 25 4
gpt4 key购买 nike

我有一个这样的 json 对象

  {
"value": "0",
"minute": "2019-04-16T01:48",
"action": "verb",
"label": "noun",
"id": "appid1"
},
{
"value": "7",
"minute": "2019-04-16T01:49",
"action": "verb",
"label": "noun",
"id": "appid1"
},
{
"value": "18",
"minute": "2019-04-16T01:50",
"action": "verb",
"label": "noun",
"id": "appid1"
},
{
"value": "0",
"minute": "2019-04-16T01:31",
"action": "verb",
"label": "noun",
"id": "appid2"
},
{
"value": "19",
"minute": "2019-04-16T01:51",
"action": "verb",
"label": "noun",
"id": "appid2"
},
{
"value": "19",
"minute": "2019-04-16T01:52",
"action": "verb",
"label": "noun",
"id": "appid2"
},
{
"value": "19",
"minute": "2019-04-16T01:53",
"action": "verb",
"label": "noun",
"id": "appid1"
},
{
"value": "18",
"minute": "2019-04-16T01:54",
"action": "verb",
"label": "noun",
"id": "appid1"
},
{
"value": "17",
"minute": "2019-04-16T01:55",
"action": "verb",
"label": "noun",
"id": "appid1"
}

我想要的是创建三个桶(A、B、C)。存储桶 A 具有前三个 appid1 对象,而存储桶 B 具有 appid2 对象,而存储桶 C 具有第三个也是最后一组 appid1 对象。

我试过这样做

let startIndex = 0;
let endIndex = -1;

let currentAppID = "appid1"
data.forEach((d, index)=> {
if(d["label"] === 'noun' && d["id"]=== currentGameId && d["action"]==="verb") {
startIndex = index
}

if(d["label"] === 'noun' && d["id"]!== currentGameId && d["event.action"]==="verb") {
endIndex = index
}
})

let bucketItems = data.slice(startIndex,endIndex)

但是这段代码完全给我荒谬的结果。你能告诉我我在这里做错了什么吗?

谢谢

最佳答案

您可以减少数组并检查last 对象和实际对象o 是否具有相同的id,否则添加一个新组.

var data = [{ value: "0", minute: "2019-04-16T01:48", action: "verb", label: "noun", id: "appid1" }, { value: "7", minute: "2019-04-16T01:49", action: "verb", label: "noun", id: "appid1" }, { value: "18", minute: "2019-04-16T01:50", action: "verb", label: "noun", id: "appid1" }, { value: "0", minute: "2019-04-16T01:31", action: "verb", label: "noun", id: "appid2" }, { value: "19", minute: "2019-04-16T01:51", action: "verb", label: "noun", id: "appid2" }, { value: "19", minute: "2019-04-16T01:52", action: "verb", label: "noun", id: "appid2" }, { value: "19", minute: "2019-04-16T01:53", action: "verb", label: "noun", id: "appid1" }, { value: "18", minute: "2019-04-16T01:54", action: "verb", label: "noun", id: "appid1" }, { value: "17", minute: "2019-04-16T01:55", action: "verb", label: "noun", id: "appid1" }],
result = data.reduce((r, o, i, { [i - 1]: last }) => {
if (!last || o.id !== last.id) r.push([]);
r[r.length - 1].push(o);
return r;
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 根据键值对过滤对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55704960/

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