我正在尝试迭代对象数组以创建一个更适合我未来计划的新对象。一切正常,直到我在地图中添加了一个 if 语句,但我不知道为什么?
const TestArray = [{
value: 0.2,
Time: '1980',
Region: 'Oklahoma',
RegionNumber: '1620',
validTo: 2017
},
{
value: 0.3,
Time: '1983',
Region: 'Oklahoma',
RegionNumber: '1620',
validTo: 2017
},
{
value: 0.2,
Time: '1986',
Region: 'Oklahoma',
RegionNumber: '1620',
validTo: 2017
},
{
value: 0.2,
Time: '1988',
Region: 'Oklahoma',
RegionNumber: '1620',
validTo: 2017
},
{
value: 0.2,
Time: '2018',
Region: 'Oklahoma',
RegionNumber: '1620',
validTo: 2017
}
]
console.log("This works fine:")
console.log(Object.fromEntries(TestArray.map((item) => [item["Time"], item["value"]])))
console.log("but when adding filter it crashes:") …Run Code Online (Sandbox Code Playgroud)尝试将对象数组转换为嵌套对象。有没有一个好的方法呢?以及如何根据数组长度来制作它?
工作但不通用: 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"]
}
]; …Run Code Online (Sandbox Code Playgroud) 由于代码显示选项默认有一个“chosenValue”,但是我必须将其更改为默认在下拉列表中显示的内容,否则下拉列表为空。如何才能使页面加载时默认值显示“chosenValue”?这是一个codesandbok示例:https://codesandbox.io/s/practical-noether-dwt52t? file=/src/App.js:0-1421
import "./styles.css";
import {
FormControl,
InputLabel,
Select,
MenuItem,
OutlinedInput
} from "@mui/material";
import { useState } from "react";
export default function App() {
const [options, setOptions] = useState({
chosenValue: {
label: "apple",
color: "green"
},
aviableValues: [
{ label: "apple", color: "red" },
{ label: "Orange", color: "Orange" },
{ label: "pear", color: "green" }
]
});
const handleContentChange = (event) => {
setOptions((prevState) => ({
...prevState,
chosenValue: event.target.value
}));
};
return (
<>
{options.chosenValue && ( …Run Code Online (Sandbox Code Playgroud)