[英]Array of object into a nested object for every value in the array
试图将一个对象数组变成一个嵌套的 object。有什么好的方法吗? 以及如何根据数组长度制作它?
工作但不通用: 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...
}
}
下面的代码有效,但仅针对两个不同的选项进行了硬编码。 我希望它能够嵌套数组的长度。 所以假设另一个 object 的年龄是 {"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());
您可以使用递归 function 来完成。
下面的 function 将每个options
数组减少为 object,然后如果原始sorting
数组还rest
元素,则继续填充该 object。
const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({
...a,
[v]: rest.length ? fn(rest): null
}), {});
const result = fn(sorting);
除了reduce()
方法之外,上面的代码还使用了 object 和数组解构和扩展语法。
完整片段:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.