gpt4 book ai didi

javascript - 使用新对象中的值更新原始对象中的值,如果不存在则将值设置为 0

转载 作者:行者123 更新时间:2023-12-01 00:39:52 25 4
gpt4 key购买 nike

我有 2 个对象。过滤器和新过滤器

const filters = {
city: [
{
key: "Brooklyn",
doc_count: 230
},
{
key: "New York",
doc_count: 224
},
{
key: "Queens",
doc_count: 18
},
{
key: "Bronx",
doc_count: 6
},
{
key: "Staten Island",
doc_count: 5
},
{
key: "Long Island City",
doc_count: 3
},
{
key: "Rockaway Beach",
doc_count: 1
}
],
roomType: [
{
key: "Entire home/apt",
doc_count: 276
},
{
key: "Private room",
doc_count: 205
},
{
key: "Shared room",
doc_count: 6
}
]
};

const newFilters = {
city: [
{
key: "Bronx",
doc_count: 6
}
],
roomType: [
{
key: "Private room",
doc_count: 4
},
{
key: "Entire home/apt",
doc_count: 2
}
]
};

过滤器中的 doc_count 值需要使用 newFilters 的 doc_values 进行更新。返回一个新对象。

这部分我正在工作。请参阅此处:

https://codesandbox.io/s/suspicious-raman-k6x2f

但是,它正在更新所有现有值并保持不变的值不变。这是预料之中的。但就我而言,如果没有任何内容需要更新,我需要它设置 doc_count: 0

例如:在示例中,它返回 roomType,它按预期更新私有(private)房间和整个住宅/公寓,但是

键:“共享房间”
doc_count: 6

这应该是

键:“共享房间”
doc_count: 0

这是因为如果它没有返回更新,则没有可用的项目。

它应该看起来像这样:

const newObject = {
city: [
{
key: "Brooklyn",
doc_count: 0
},
{
key: "New York",
doc_count: 0
},
{
key: "Queens",
doc_count: 0
},
{
key: "Bronx",
doc_count: 6
},
{
key: "Staten Island",
doc_count: 0
},
{
key: "Long Island City",
doc_count: 0
},
{
key: "Rockaway Beach",
doc_count: 0
}
],
roomType: [
{
key: "Entire home/apt",
doc_count: 276
},
{
key: "Private room",
doc_count: 205
},
{
key: "Shared room",
doc_count: 0
}
]
};

最佳答案

像这样怎么样:

const newObj = Object.keys(filters).map(filterKey => {
const oldFilter = filters[filterKey];
const newFilter = newFilters[filterKey];
return oldFilter.map(f => {
const matchingNewFilter = newFilter.find(nf => nf.key === f.key);
return matchingNewFilter || { ...f, doc_count: 0 };
});
});

此处的沙箱:https://codesandbox.io/s/proud-haze-n4vsu

更新:上面返回一个数组,这里是返回一个对象的版本:

const update = (...args) =>
Object.keys(args[0]).reduce((acc, k) => {
acc[k] = args[0][k].map(
f =>
args[1][k].find(nf => nf.key === f.key) || {
...f,
doc_count: 0
}
);
return acc;
}, {});

console.log(update(filters, newFilters));

此处更新了沙箱:https://codesandbox.io/s/dry-pine-oxpvf

关于javascript - 使用新对象中的值更新原始对象中的值,如果不存在则将值设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57795741/

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