gpt4 book ai didi

javascript 对象数组转换为值列表

转载 作者:行者123 更新时间:2023-12-01 02:20:28 25 4
gpt4 key购买 nike

我有一个如下所示的对象列表,我想将其转换为按 id 的值列表。

Original = [
{id: 1, value: 12.2494, time: "00:00:00.14"},
{id: 1, value: 4.5141, time: "00:00:01.138"},
{id: 1, value: 2.85930, time: "00:00:02.138"},
{id: 1, value: 1.0364, time: "00:00:03.146"},
{id: 2, value: 4.3510, time: "00:09:15.157"},
{id: 2, value: 3.90, time: "00:09:16.115"},
{id: 2, value: 3.544, time: "00:09:17.116"},
{id: 2, value: 3.247, time: "00:09:18.157"}
]

预期结果

data[1]={value:[12.494, 4.5141...],time: ["00:00:00.14","00:00:01.138"]...} 
data[2]={value:[4.3510, 3.90...],time: ["00:09:15.157","00:09:16.115"]...}

我尝试过类似的方法,但只返回一个值

var data= {};
original.forEach(function(item) {
var id = item.id;
data[id] = {
value:[],
time:[]
}
data[id].value.push(item['value']);
data[id].time.push(item['time']);
})

最佳答案

您可以使用数组中的函数reduce

检查累加器中当前的id

如果存在,则推送到已存储的时间

否则创建一个模板对象并推送时间

var Original=[{id: 1, value: 12.2494,  time: "00:00:00.14"},{id: 1, value: 4.5141, time: "00:00:01.138"},{id: 1, value: 2.85930,  time: "00:00:02.138"},{id: 1, value: 1.0364,  time: "00:00:03.146"},{id: 2, value: 4.3510,  time: "00:09:15.157"},{id: 2, value: 3.90, time: "00:09:16.115"},{id: 2, value: 3.544, time: "00:09:17.116"},{id: 2, value: 3.247,  time: "00:09:18.157"}];

var data = Original.reduce((a, c) => {
var current = (a[c.id] || (a[c.id] = {value: [], time: []}));
current.value.push(c.value);
current.time.push(c.time);

return a;
}, {});

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

关于javascript 对象数组转换为值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247189/

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