gpt4 book ai didi

javascript - 如何从两个对象数组中减去或减去特定值?

转载 作者:行者123 更新时间:2023-12-02 22:43:57 25 4
gpt4 key购买 nike

说实话,我来这里是为了问一个简单的问题,这让我浪费了太多时间这是示例数据

    const demo1 = [
{ count: 156, monthCount: 1, year: 2018 },
{ count: 165, monthCount: 2, year: 2018 },
{ count: 103, monthCount: 3, year: 2018 },
{ count: 60, monthCount: 4, year: 2018 }
]
const data2 = [
{ count: 100, monthCount: 1, year: 2019 },
{ count: 55, monthCount: 2, year: 2019 },
{ count: 99, monthCount: 3, year: 2019 },
{ count: 130, monthCount: 4, year: 2019 }
]

我想获取 data3,它是 data2 - data1 及其 key 预期输出看起来像这样

[
{count: 56, monthCount: 1 },
{count: 100, monthCount: 2 },
{count: 60, monthCount: 3 },
{count: 70, monthCount: 4 }
]

最佳答案

如果您想减去data2 - data1,那么您可以通过vanilla JavaScript 来完成。让我举个例子。您的数据:

const data1 = [
{ count: 156, monthCount: 1, year: 2018 },
{ count: 165, monthCount: 2, year: 2018 },
{ count: 103, monthCount: 3, year: 2018 },
{ count: 60, monthCount: 4, year: 2018 }
];
const data2 = [
{ count: 100, monthCount: 1, year: 2019 },
{ count: 55, monthCount: 2, year: 2019 },
{ count: 99, monthCount: 3, year: 2019 },
{ count: 130, monthCount: 4, year: 2019 }
];

一个例子:

const combined = data1.concat(data2);
console.log(`combined, not calculated`, combined);

const desired = [...combined.reduce((r, {monthCount, count}) => {
const key = monthCount;

const item = r.get(key) || Object.assign({}, {
count: 0,
monthCount: monthCount
});

if (item.count === 0)
item.count = -count;
else
item.count += +count;

return r.set(key, item);
}, new Map).values()];

console.log(`desired: `, desired)

输出:

[
{count: -56, monthCount: 1},
{count: -110, monthCount: 2},
{count: -4, monthCount: 3},
{count: 70, monthCount: 4},
]

关于javascript - 如何从两个对象数组中减去或减去特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58484157/

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