【发布时间】:2021-09-10 03:37:55
【问题描述】:
这是代码框链接:https://codesandbox.io/s/filter-sr3ci?file=/src/App.js:24-1548
我有这些 JSON 数据,我正在尝试过滤其他人的所有值并同时计算它们。示例:
"1" 中其他人的价值观之一是书:
{
displayName: "Person3",
"1": { others: "book", items1: { car: true, bike: true } },
"2": {
others: "",
items2: { bike: true, motor: true, truck: true }
}
},
{
displayName: "Person4",
"1": { others: "book", items1: { car: true, bike: true } },
"2": { others: "", items2: { truck: true, bike: true } }
},
我想在屏幕上显示如下内容:
"1" data:
Book - 2
与“2”相同,具有风扇和电线的值:
"2" data:
fan - 3
wire - 2
我尝试过滤它,但它在这段代码中有一条红线,并且有一个错误提示“解析错误”:
const others1 = data.filter((d) => d."1"?.others !== "")
以下是代码:
export default function App() {
const data = [
{
displayName: "Person1",
"1": { others: "", items1: { car: true, motor: true } }
},
{
displayName: "Person2",
"1": {
others: "",
items1: { car: true, motor: true, bike: true }
},
"2": { items2: { truck: true, bike: true }, others: "wire" }
},
{
displayName: "Person3",
"1": { others: "book", items1: { car: true, bike: true } },
"2": {
others: "wire",
items2: { bike: true, motor: true, truck: true }
}
},
{
displayName: "Person4",
"1": { others: "book", items1: { car: true, bike: true } },
"2": { others: "", items2: { truck: true, bike: true } }
},
{
displayName: "Person5",
"1": { others: "", items1: { motor: true, car: true } },
"2": {
items2: { truck: true, bike: true },
others: "fan"
}
},
{
displayName: "Person6",
"2": {
items2: { car: true, truck: true, motor: true },
others: "fan"
}
},
{
"1": { others: "book", items1: { motor: true, car: true } },
"2": {
items2: { car: true, truck: true },
others: "fan"
},
displayName: "Person7"
}
];
const others1 = data.filter((d) => d."1"?.others !== "")
// console.log(others1.length);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
【问题讨论】:
-
应该是
data.filter((d) => d["1"].?others !== "") -
为什么不使用数组而不是带有数字键的对象?
标签: javascript reactjs json