gpt4 book ai didi

javascript - 在javascript中合并数组中的 map 数据

转载 作者:行者123 更新时间:2023-11-29 10:58:29 26 4
gpt4 key购买 nike

这是我当前的数组:

{ entity: 'A', type: 'request', requestUrl: 'val1' },
{ entity: 'A', type: 'response', responseUrl: 'val1' },
{ entity: 'B', type: 'request', requestUrl: 'val1' },
{ entity: 'B', type: 'response', responseUrl: 'val1' },
{ entity: 'C', type: 'request', requestUrl: 'val1' },
{ entity: 'C', type: 'response', responseUrl: 'val1' },
{ entity: 'D', type: 'request', requestUrl: 'val1' },
{ entity: 'D', type: 'response', responseUrl: 'val1' },
{ entity: 'DADA', type: '', responseUrl: 'val1' }

每一行包含一个名为“entity”的属性,它有两行:一个对应于请求,另一个对应于响应。我需要合并请求行和响应行,并将数据仅作为一行。 (属性“类型”在合并行中无关紧要,但需要具有所有其他属性)。所以解决方案是这样的:

[{"entity":"A","type":"response","requestUrl":"val1","responseUrl":"val1"},
{"entity":"B","type":"response","requestUrl":"val1","responseUrl":"val1"},
{"entity":"C","type":"response","requestUrl":"val1","responseUrl":"val1"},
{"entity":"D","type":"response","requestUrl":"val1","responseUrl":"val1"}]

目前,这就是我所拥有的: https://www.w3schools.com/code/tryit.asp?filename=FUHGQN2JON75

不确定这是否是最好的方法。欢迎就如何改进此解决方案提出建议。

谢谢。

最佳答案

一种选择是使用reduce 将您的数组分组到一个对象中。使用 entity 作为键。使用 Object.assign 转换对象。使用 Object.values 将对象转换为数组。

var arr = [{"entity":"A","type":"request","requestUrl":"val1"},{"entity":"A","type":"response","responseUrl":"val1"},{"entity":"B","type":"request","requestUrl":"val1"},{"entity":"B","type":"response","responseUrl":"val1"},{"entity":"C","type":"request","requestUrl":"val1"},{"entity":"C","type":"response","responseUrl":"val1"},{"entity":"D","type":"request","requestUrl":"val1"},{"entity":"D","type":"response","responseUrl":"val1"},{"entity":"DADA","type":"","responseUrl":"val1"}];

var result = Object.values(arr.reduce((c, v) => {
c[v.entity] = Object.assign(c[v.entity] || {}, v);
return c;
}, {}));

console.log(result);

关于javascript - 在javascript中合并数组中的 map 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51945943/

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