gpt4 book ai didi

javascript - 如何使用另一个数组中其他对象的键替换对象数组中的值

转载 作者:行者123 更新时间:2023-12-01 00:42:18 24 4
gpt4 key购买 nike

我有 2 个对象数组

注意:状态和原始语言无法手动设置,因为它们一直在变化,这些是自定义字段。字段中的 slugs 构成了所有自定义字段。

const items = [
{
name: 'Surviving the Game',
status: 'ffdb29ba075fcbc0b71295c31a13d64f',
original-language: 'b4ebbe06702794d1cf375274197267b2',
},
{
name: 'Some Movie',
status: 'cd53c082c6ca9e7d3ec66890e66c01f3',
original-language: '7a1cac74217747933bb3915888dea090',
},
];
const fields = [
{
slug: 'status',
options: [
{
name: 'Released',
id: 'ffdb29ba075fcbc0b71295c31a13d64f',
},
{
name: 'Upcoming',
id: 'cd53c082c6ca9e7d3ec66890e66c01f3',
},
],
},
{
slug: 'original-language',
options: [
{
name: 'de',
id: 'b4ebbe06702794d1cf375274197267b2',
},
{
name: 'en',
id: '7a1cac74217747933bb3915888dea090',
},
],
},
];

[items] 中的状态和原始语言具有与相应字段数组中的选项匹配的 id 值。

我正在尝试返回 [items] 的新数组,其名称来自具有匹配 id 的选项。

例如:

[
{
name: 'Surviving the Game',
status: 'Released',
original-language: 'de',
},
{
name: 'Some Movie',
status: 'Upcoming',
original-language: 'en',
},
];

我该如何使用 ES6/7 来解决这个问题?

我不知道从哪里开始

最佳答案

我将通过创建一个 lookup 对象来实现此目的,该对象包含对您的状态和语言的查找。然后,您可以在映射项目时使用此查找对象。

var items = [
{
name: 'Surviving the Game',
status: 'ffdb29ba075fcbc0b71295c31a13d64f',
"original-language": 'b4ebbe06702794d1cf375274197267b2'
},
{
name: 'Some Movie',
status: 'cd53c082c6ca9e7d3ec66890e66c01f3',
"original-language": '7a1cac74217747933bb3915888dea090'
}
];

var fields = [
{
slug: 'status',
options: [
{
name: 'Released',
id: 'ffdb29ba075fcbc0b71295c31a13d64f'
},
{
name: 'Upcoming',
id: 'cd53c082c6ca9e7d3ec66890e66c01f3'
}
]
},
{
slug: 'original-language',
options: [
{
name: 'de',
id: 'b4ebbe06702794d1cf375274197267b2'
},
{
name: 'en',
id: '7a1cac74217747933bb3915888dea090'
}
]
}
];

const lookup = {};

fields.forEach(field => {
lookup[field.slug] = field.options.reduce((all, option) => ({
...all,
[option.id]: option.name
}), {})
});

const translatedItems = items.map(item => {
return Object.entries(item)
.reduce((all, [key, val]) => ({
...all,
[key]: lookup[key] ? lookup[key][val] : val
}),{});
});

console.log(translatedItems);

关于javascript - 如何使用另一个数组中其他对象的键替换对象数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639555/

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