gpt4 book ai didi

javascript - 将对象的两个位置链接到单个位置

转载 作者:行者123 更新时间:2023-12-02 02:05:56 24 4
gpt4 key购买 nike

我以这种方式收到对象

const tests = [
{id: 0, vencimiento: "231216000000"},
{id: 0, monto: "99000"},
{id: 1, vencimiento: "230117000000"},
{id: 1, monto: "198000"},
{id: 2, vencimiento: "230217000000"},
{id: 2, monto: "297000"},
];

我想合并具有相同 id 的职位

const resultado= [
{id: 0, vencimiento: "231216000000", monto: "99000"},
{id: 1, vencimiento: "230117000000", monto: "198000"},
{id: 2, vencimiento: "230217000000", monto: "297000"},
];

最佳答案

您可以使用Array.prototype.reduce()并返回一个普通对象,
然后使用 Object.values() 获得您想要的结果:

const tests = [
{id: 0, vencimiento: "231216000000"},
{id: 0, monto: "99000"},
{id: 1, vencimiento: "230117000000"},
{id: 1, monto: "198000"},
{id: 2, vencimiento: "230217000000"},
{id: 2, monto: "297000"},
];

const res = Object.values(tests.reduce((acc, curr) => {
if(!acc[curr.id]) {
acc[curr.id] = {...curr}
} else {
acc[curr.id] = {
...acc[curr.id],
...curr
}
}

return acc;
}, {}));

console.log(res);

Array.prototype.reduce()
Object.values()

关于javascript - 将对象的两个位置链接到单个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68446259/

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