如何解决从嵌套数组 Json 中获取可用数字
我得到的数据的公式如下。我正在努力使用 reduce 或 map 从中获取任何可用数据
const data = [
{
id: 25,status: 1,description: "No Description",length: 4,data: [
{
id: 43,comment: "Comment1",eventTimestamp: 1541027189000,intensity: 29
},{
comment: "Comment2",eventTimestamp: 1541027191000,intensity: 33
},{
id: 45,comment: "Comment3",eventTimestamp: 1541027193000,intensity: 30
}
],tTypes: [
{
id: 3,label: "Johnny",certainty: "TEST",comment: "Test Purposes Only",icon: "bottle",number: 0
}
]
}
];
我试过扁平化,我试过两次迭代 JSON,但我似乎最终得到了“NaN”或未定义。我希望能够按时间顺序(使用时间戳)对它们进行排序,从强度值中获取混合/最大值/平均值等等。我已经弄清楚了更高级别的长度,但似乎无法弄清楚其余部分。有人能指出我正确的方向吗?
export default function App() {
let tTypesArray = data.map((a) => a.tTypes);
let Walker = tTypesArray.reduce((a,tTypes) => tTypes.label === "Johnny" ? ++a : a,0);
console.log(Walker);
console.log(tTypesArray[0].label);
console.log([].concat(...data)
.map(data => data.tTypes.number)
.reduce((a,b) => a + b))
console.log([].concat(...data).reduce((a,{ tTypes: { id }}) => id,0))
return <div className="App">ARG!</div>;
}
是我尝试过的一些示例。 https://codesandbox.io/s/purple-cache-ivz1y?file=/src/App.js 是沙盒的链接。
解决方法
我从您的问题中了解到,您需要循环 data
并且对于 data
中的每个元素,您要提取值并进行一些计算。
首先,您需要循环输入数据。我将使用Array.forEach:
data.forEach(element => { ... })
现在我们有了一个循环,我们可以访问每个元素属性并提取我们想要的信息。例如,假设您想按时间戳按升序 sort 评论:
const sortedComments = element.data.sort((a,b) => a.eventTimestamp - b.eventTimestamp);
console.log(sortedComments)
现在假设您想要评论中的最小、最大和平均强度。有几种方法可以得到它。这是一个算法:
let min = Infinity;
let max = -Infinity;
let sum = 0;
for(comment of sortedComments) {
if(comment.intensity < min) {
min = comment.intensity;
}
if(comment.intensity > max) {
max = comment.intensity;
}
sum += comment.intensity;
}
const avg = sum / sortedComments.length;
console.log({min,max,avg})
综合起来:
const data = [
{
id: 25,confirmationStatus: 1,description: "No Description",length: 4,data: [
{
id: 43,comment: "Comment1",eventTimestamp: 1541027189000,intensity: 29
},{
comment: "Comment2",eventTimestamp: 1541027191000,intensity: 33
},{
id: 45,comment: "Comment3",eventTimestamp: 1541027193000,intensity: 30
}
],tTypes: [
{
id: 3,label: "Johnny",certainty: "TEST",comment: "Test Purposes Only",icon: "bottle",number: 0
}
]
}
];
data.forEach(element => {
const sortedComments = element.data.sort((a,b) => a.eventTimestamp - b.eventTimestamp);
console.log(sortedComments);
let min = Infinity;
let max = -Infinity;
let sum = 0;
for(comment of sortedComments) {
if(comment.intensity < min) {
min = comment.intensity;
}
if(comment.intensity > max) {
max = comment.intensity;
}
sum += comment.intensity;
}
const avg = sum / sortedComments.length;
console.log({min,avg});
let walker = element.tTypes.reduce(
(a,tType) => (tType.label === "Johnny" ? ++a : a),0
);
console.log(walker)
});
我希望它能让你朝着正确的方向前进。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。