gpt4 book ai didi

javascript - 通过另一个预定义的数组元素作为键来重构 JavaScript 对象数组

转载 作者:行者123 更新时间:2023-11-28 12:57:45 25 4
gpt4 key购买 nike

我也在 jsbin 上放置了相同的代码:https://jsbin.com/literefeqo/edit?js,console

说明

我有一个对象数组 (1),并且想要转换(可能使用 map )该对象。转换标准是给定数组 (2),对应于 arrObj 中的 german 属性。这意味着,如果 arrObj 中有一个 german 属性,则应将其“复制”出来,并应将其用作生成 resultObj (3) 的键。如果没有 german 属性,那么键应该是“未知”或其他。

注意:resultObj 中可以有更多条目,例如蒙塔格。这样 resultObj.Montag[i] 应该是一个对象数组。

(1) 对象数组

const arrObj = [
{
"day": {
"string": "Monday",
"Number": 1
},
"description": {
"type": "string",
"value": "The first day of the week"
},
"german": {
"type": "string",
"value": "Montag"
}
},
{
"day": {
"string": "Tuesday",
"Number": 2
},
"description": {
"type": "string",
"value": "The second day of the week"
}
},
{
"day": {
"string": "Wednesday",
"Number": 3
},
"description": {
"type": "string",
"value": "The third day of the week"
},
"german": {
"type": "string",
"value": "Mittwoch"
}
}
];

(2) 应该成为新对象的键的数组

const germanDays = ["Montag","Dienstag","Mittwoch","Donnerstag"];

(3) 结果应如下所示

const resultObj =   {
"Montag": [
{
"day": {
"string": "Monday",
"Number": 1
},
"description": {
"type": "string",
"value": "The first day of the week"
},
"german": {
"type": "string",
"value": "Montag"
}
}
],
"Dienstag": [
{}
],
"Mittwoch": [
{
"day": {
"string": "Wednesday",
"Number": 3
},
"description": {
"type": "string",
"value": "The third day of the week"
},
"german": {
"type": "string",
"value": "Mittwoch"
}
}
],
"Donnerstag": [
{}
],
"Unknown": [
{
"day": {
"string": "Tuesday",
"Number": 2
},
"description": {
"type": "string",
"value": "The second day of the week"
}
}
]

};

最佳答案

(possibly using map)

map,是数组到数组的映射,更合适的函数是reduce。

这是一个示例。

const germanDays = ["Montag","Dienstag","Mittwoch","Donnerstag"]

const arrObj = [
{
"day": {
"string": "Monday",
"Number": 1
},
"description": {
"type": "string",
"value": "The first day of the week"
},
"german": {
"type": "string",
"value": "Montag"
}
},
{
"day": {
"string": "Tuesday",
"Number": 2
},
"description": {
"type": "string",
"value": "The second day of the week"
}
},
{
"day": {
"string": "Wednesday",
"Number": 3
},
"description": {
"type": "string",
"value": "The third day of the week"
},
"german": {
"type": "string",
"value": "Mittwoch"
}
},
{
"day": {
"string": "Monday",
"Number": 1
},
"description": {
"type": "string",
"value": "Just another text is here"
},
"german": {
"type": "string",
"value": "Montag"
}
}
];

const ret = germanDays.reduce((a, v) => {
const f = arrObj.filter(f => f.german && f.german.value === v);
a[v] = f;
return a;
}, {
"Unknown": arrObj.filter(f => !f.german)
});


console.log(ret);

关于javascript - 通过另一个预定义的数组元素作为键来重构 JavaScript 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53595340/

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