mat*_*eva 6 javascript node.js
尝试将对象数组转换为嵌套对象。有没有一个好的方法呢?以及如何根据数组长度来制作它?
工作但不通用: 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"
]
}
]
Run Code Online (Sandbox Code Playgroud)
我想要的是:
value: {
"Region": "Oklahoma",
"HighestDegree": {
"HighSchool": {
"male": null,
"female":null
},
"Undergraduate":{
"male": null,
"female":null
}
//and so on...
}
}
Run Code Online (Sandbox Code Playgroud)
下面的代码可以工作,但仅针对两个不同的选项进行了硬编码。我希望它能够嵌套数组的长度。因此,假设另一个对象是年龄,它将是 {"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());
Run Code Online (Sandbox Code Playgroud)
您可以使用递归函数来完成它。
下面的函数将每个数组缩减options为一个对象,然后如果rest原始sorting数组中还剩下元素,则继续填充该对象。
const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({
...a,
[v]: rest.length ? fn(rest): null
}), {});
const result = fn(sorting);
Run Code Online (Sandbox Code Playgroud)
除了该reduce()方法之外,上面的代码还使用了对象和数组解构以及扩展语法。
完整片段:
const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({
...a,
[v]: rest.length ? fn(rest): null
}), {});
const result = fn(sorting);
Run Code Online (Sandbox Code Playgroud)