具有动态键的对象的变平数组,仅与“ _abs”的对象相加的值以关键名称
我有一系列看起来像这样的对象:
[{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...}]
每个对象中的元素可以n
元素,每个对象都由_perc和_abs值组成。 我想将数组仅减少到1个条目,然后将每个_abs值总结,_perc可以是其他任何东西,例如“ - ”。
预期的结果是:
{"A_abs": 16, "A_perc": "-" "B_abs": 16, "B_perc": "-" "C_abs": x, "C_perc": "-", ...}
解决方案这个问题并没有完全指出我知道如何使函数仅总和“ _abs”值。
如何适应此函数仅总和_abs值,而对对象的条目有多少个条目?
var data = [{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2}],
result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});
console.log(result);
I have an array of objects that looks like this:
[{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...}]
There can be up to n
elements in each object, each one consists of a _perc and an _abs value.
I want to reduce the array to only 1 entry and sum each _abs value, the _perc can be anything else, like "-".
An expected result would be:
{"A_abs": 16, "A_perc": "-" "B_abs": 16, "B_perc": "-" "C_abs": x, "C_perc": "-", ...}
The solution of this question does not fully statisfy me because I don't know how to adapt the function to only sum the "_abs" values.
How to adapt this function to only sum the _abs values, regardles of how many entries the object has?
var data = [{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2}],
result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});
console.log(result);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以检查
key
以_abs
结束,并且仅当它添加值时,您只需分配> -
的值即可。You can check if the
key
ends with_abs
and only if it does you add the values else you simply assign a value of-
.