gpt4 book ai didi

javascript - 对象数组到数组中每个值的嵌套对象中

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

试图将对象数组转换为嵌套对象。有什么好的方法吗?以及如何根据数组长度制作它?
工作但不是通用的:
https://codesandbox.io/s/thirsty-roentgen-3mdcjv?file=/src/App.js
我有的:

sorting: [
{
"id": "HighestDegree",
"options": [
"HighSchool",
"Undergraduate",
"Bachelor",
"Master",
"Doctor"
]
},
{
"id": "gender",
"options": [
"male",
"female"
]
}
]
我想要的是:
value: {
"Region": "Oklahoma",
"HighestDegree": {
"HighSchool": {
"male": null,
"female":null
},
"Undergraduate":{
"male": null,
"female":null
}
//and so on...
}
}
下面的代码有效,但仅针对两个不同的选项进行了硬编码。我希望它能够嵌套数组的长度。因此,假设另一个对象是年龄,它将是 {"HighSchool":{male:{"<25":null,"25-35":null}}} 等。
function testSortingArray() {
let sorting = [
{
id: "HighestDegree",
options: ["HighSchool", "Undergraduate", "Bachelor", "Master", "Doctor"]
},
{
id: "gender",
options: ["male", "female"]
}
];
let GoalArray = {};
if (sorting.length > 0) {
sorting[0].options.map((firstArray) => {
let currObject = {};
sorting[1].options.map((secondOption) => {
currObject[secondOption] = null;
});
GoalArray[firstArray] = currObject;
});
}
return GoalArray;
}
console.log(testSortingArray());

最佳答案

您可以使用递归函数来完成。
reduces下面的函数每options数组到一个对象,然后继续填充该对象,如果有 rest原始 sorting 中留下的元素大批。

const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({
...a,
[v]: rest.length ? fn(rest): null
}), {});
const result = fn(sorting);
除了 reduce()方法,上面的代码使用了对象和数组 destructuringspread syntax .

完整片段:

const sorting = [{
"id": "HighestDegree",
"options": [
"HighSchool",
"Undergraduate",
"Bachelor",
"Master",
"Doctor"
]
}, {
"id": "gender",
"options": [
"male",
"female"
]
}, {
"id": "age",
"options": [
"<25",
"25-35"
]
}];

const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({
...a,
[v]: rest.length ? fn(rest): null
}), {});
const result = fn(sorting);

console.log(result);

关于javascript - 对象数组到数组中每个值的嵌套对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71907005/

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