【发布时间】:2021-12-07 09:57:14
【问题描述】:
首先,如果这通常是一件简单的事情,我深表歉意,但我在 JS 方面并不是特别有经验。我正在尝试在 Plotly.js 中为当前保存原始 JSON 的工作站点制作一些图表。我们有一个 JSON 格式:
stuff = [{"name": "shark", "location": "somewhere", "number":10},
{"name": "shark", "location": "somewhereelse", "number":50},
{"name": "shark", "location": "somewhere", "number":25},
{"name": "turtle", "location": "anotherplace", "number":1},
{"name": "elephant", "location": "greatplace", "number":50},
{"name": "elephant", "location": "greatplace", "number":75}
我需要结果看起来像:
computed = [{"name":"shark", "location":"somewhere", "number":35},
{"name":"shark", "location":"somewhereelse", "number":50},
{"name":"turtle", "location":"anotherplace", "number":1},
{"name":"elephant", "location":"greatplace", "number":125}
所有名称都按位置分组,并且该组中的所有数字相加。然后,我将使用这个计算得到的 JSON 与 Plotly.js 一起绘制我已经构建的一些函数。
我想我可以将问题简化为:
forEach((item) => {
x.push(item['location']
y.push(y += stuff.number where stuff.location === x[-1])
}
但这也意味着我将获得与 stuff 中相同的行数,只是计算和绘制。恐怕我想不通了。
任何帮助将不胜感激。
【问题讨论】:
-
请注意,如果您看到
myVariable = [{",数据是一个JS对象,而不是JSON。
标签: javascript json