简体   繁体   English

如何在不嵌套 Object.entries 的情况下在 object 中添加值?

[英]How can I add the values in my object without nesting Object.entries?

My JSON looks something like this:我的 JSON 看起来像这样:

const json = {
  "08/23/2022": {
    "One": 254,
    "Two": 92,
    "Three": 8
  },
  "08/13/2022": {
    "One": 327,
    "Two": 86,
  },
  "08/14/2022": {
    "One": 431
  },
}

I need to add all of these values, regardless of what the key is.无论键是什么,我都需要添加所有这些值。 In this case, the calculation would be 254+92+8+327+86+431, and the output would be 1198. Previously I had just been counting the first ([0]) value but I just realized that's not correct and the only solution I can think of is essentially nesting loops, but that doesn't seem like the cleanest or most efficient way to accomplish this.在这种情况下,计算将是 254+92+8+327+86+431,而 output 将是 1198。之前我刚刚计算了第一个 ([0]) 值,但我才意识到这是不正确的,并且我能想到的唯一解决方案本质上是嵌套循环,但这似乎不是实现这一目标的最干净或最有效的方法。 This is my current code for reference:这是我当前的参考代码:

for (const [key, value] of Object.entries(json)) {
  Object.entries(value).forEach(val => output += val[1])
}

So what's the correct way?那么正确的方法是什么?

There are fundamentally two dimensions to go through - the date-object pairs of the top level object, and then the digit-number pairs of the inner objects. go 基本上有两个维度 - 顶级 object 的日期对象对,然后是内部对象的数字数字对。 So there really isn't any decent way around logic that accounts for two levels of nesting.因此,实际上没有任何体面的方法可以解决两级嵌套的逻辑。

But, a better approach would be to use Object.values - you don't care about the keys, only the values.但是,更好的方法是使用Object.values - 你不关心键,只关心值。

 const json = { "08/23/2022": { "One": 254, "Two": 92, "Three": 8 }, "08/13/2022": { "One": 327, "Two": 86, }, "08/14/2022": { "One": 431 }, }; const sum = Object.values(json).flatMap(Object.values).reduce((a, b) => a + b, 0); console.log(sum);

The result is 1198 because that's the result of 254+92+8+327+86+431.结果是 1198,因为这是 254+92+8+327+86+431 的结果。

Well, I suppose there's a way around using an Object or object iteration method twice (or more) - JSON.stringify will iterate over all nested properties anywhere - but that's silly and shouldn't be used in real code.好吧,我想有一种方法可以使用 Object 或 object 迭代方法两次(或更多)- JSON.stringify在任何地方都可以使用-但代码将愚蠢地迭代所有嵌套属性。

 const json = { "08/23/2022": { "One": 254, "Two": 92, "Three": 8 }, "08/13/2022": { "One": 327, "Two": 86, }, "08/14/2022": { "One": 431 }, }; let sum = 0;; JSON.stringify(json, (_, val) => { if (typeof val === 'number') sum += val; return val; }); console.log(sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM