我有一个像这样的对象列表,我希望通过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']);
})
答案 0 :(得分:2)
您可以使用Arrays中的reduce
函数。
检查累加器中的当前id
;
如果存在推送到已存储的values
和times
否则,请创建template object
并推送values
和times
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; }
答案 1 :(得分:0)
原始答案很有效,但是如果你对使用push有一种非理性的厌恶(如果一个对象只在一个闭包中创建和变异,它真的会改变吗?):
const 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"}
]
const data = original.reduce((x, y) => x[y.id]
? Object.assign({}, x, {
[y.id]: {
value: x[y.id]
.value
.concat(y.value),
time: x[y.id]
.time
.concat(y.time)
}
})
: Object.assign({}, x, {
[y.id]: {
value: [y.value],
time: [y.time]
}
}), {})
或者,如果数据中存在漏洞并且您不想添加未定义的内容,请缩小为唯一ID,映射该列表,过滤原始列表,缩小为合并:
const unoriginal = [
{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},
{id: 2, 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"}
]
const otherData = unoriginal.reduce((x, y) => x.includes(y.id)
? x
: x.concat(y.id), []).map(x => Object.assign({}, {
[x]: {
value: unoriginal
.filter(y => x === y.id)
.reduce((z, a) => a.value
? z.concat(a.value)
: z, []),
time: unoriginal
.filter(y => x === y.id)
.reduce((b, c) => c.time
? b.concat(c.time)
: b, [])
}
})).reduce((x, y) => Object.assign.apply(null, [x].concat(y)))