过滤数据时出现“Parsing error: Unexpected Token”错误如何解决
错误修复
你遇到的语法报错是因为非法的属性访问写法:数字/字符串类型的属性名不能通过.运算符直接访问,必须使用方括号语法,报错行修改为以下内容即可解决解析错误:
const others1 = data.filter((d) => d["1"]?.others !== "")
完整功能实现
要实现按指定键统计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" } ]; // 通用统计函数:传入指定键,返回该键下others非空值的计数对象 const getOthersCount = (targetKey) => { const countResult = {} data.forEach(item => { const othersVal = item[targetKey]?.others if (othersVal && othersVal.trim() !== '') { countResult[othersVal] = (countResult[othersVal] || 0) + 1 } }) return countResult } const count1 = getOthersCount("1") const count2 = getOthersCount("2") return ( <div className="App"> <div> <h3>"1" data:</h3> {Object.entries(count1).map(([key, count]) => ( <div key={key}>{key} - {count}</div> ))} </div> <div style={{marginTop: '20px'}}> <h3>"2" data:</h3> {Object.entries(count2).map(([key, count]) => ( <div key={key}>{key} - {count}</div> ))} </div> </div> ); }
运行后页面输出结果如下:
"1" data: book - 3 "2" data: wire - 2 fan - 3
内容的提问来源于stack exchange,提问作者JS3
相关产品推荐
相关产品推荐

