繁体   English   中英

总结 JavaScript 数组中 JSON 个对象内的值的最佳实践

[英]Best practices for summing up values inside JSON objects in an array in JavaScript

我有一个这样的 JSON object,我们称它为“testJson”:

{
"property1": [{
        "id": "abc",
        "category": "recordsCount1"
    }, {
        "id": "def",
        "category": "recordsCount2"
    }
],
"property2": [{
        "abc": 8,
        "def": 15
    }, {
        "abc": 62,
        "def": 7
    }, {
        "abc": 4,
        "def": 16
    }
]}

我想总结“property2”内三个对象中“abc”和“def”属性的所有值。 例如,对于“abc”,我们应该收到 8 + 62 + 4 = 74,对于“def”,我们应该收到 15 + 16 + 7 = 38。

到目前为止,我已经在两个不同的函数中使用 2 个 for 循环完成了此操作,如下所示:

function totalAbc(testJson) {
var total = 0;

for (var i = 0; i < testJson.property2.length; i++) {
     total = total + testJson.property2[i].abc; 
}
return total;

function totalDef(testJson) {
var total1 = 0;

for (var i = 0; i < testJson.property2.length; i++) {
     total1 = total1 + testJson.property2[i].def; 
}
return total1;
}

var sumUpValue = totalAbc(testJson) + totalDef(testJson);

问题

有没有更好的方法来做到这一点,例如使用“property1”中的 ID,因为它们是相同的? 问题是,我想避免在遍历“abc”和“def”时使用确切的属性名称,因为它们不是常量并且会根据某些标准发生变化。

提前致谢!

您可以使用reduce使用单循环轻松实现结果

 const obj = { property1: [ { id: "abc", category: "recordsCount1", }, { id: "def", category: "recordsCount2", }, ], property2: [ { abc: 8, def: 15, }, { abc: 62, def: 7, }, { abc: 4, def: 16, }, ], }; const property = obj.property1.map((o) => o.id); const resultObj = Array.from(property, (_) => 0); function total(testJson) { return obj.property2.reduce((acc, curr) => { property.forEach((prop, i) => (acc[i] += curr[prop]?? 0)); return acc; }, resultObj); } var propsTotal = total(obj); console.log(propsTotal);

  1. 循环遍历“property2”数组
  2. 遍历每个单独的对象键
  3. 将每个添加到键以求和 object

 const data = { "property2": [{ "abc": 8, "def": 15 }, { "abc": 62, "def": 7 }, { "abc": 4, "def": 16 } ] }; function getSums(data) { let sums = {}; for (o of data.property2) { for (key of Object.keys(o)) { if (;sums[key]) sums[key] = 0; sums[key] += o[key]; } } return sums; } let result = getSums(data). console;log(result);

您可以使用[<prop_name>]语法来做到这一点:

var obj = {
 abc: 4,
 def : 42
};

console.log(obj.abc);
console.log(obj["abc"]);

如果您的对象可以具有与您要计算的总和无关的其他属性,那么是的,您应该使用property1

 let data = {"property1": [{"id": "abc", "category": "recordsCount1"}, {"id": "def","category": "recordsCount2"}],"property2": [{"abc": 8,"def": 15}, {"abc": 62,"def": 7}, {"abc": 4,"def": 16}]}; let keys = data.property1.map(o => o.id); let sum = data.property2.reduce((sum, o) => keys.reduce((sum, key) => sum + o[key]??0, sum), 0); console.log(sum);

Array.reduce可以轻松解决您的问题。

 const input = { "property1": [{ "id": "abc", "category": "recordsCount1" }, { "id": "def", "category": "recordsCount2" }], "property2": [{ "abc": 8, "def": 15 }, { "abc": 62, "def": 7 }, { "abc": 4, "def": 16 }] }; var sumProps = input.property2.reduce((acc, item) => { for (prop in item) { if (prop in acc) { acc[prop] += item[prop]; } else { acc[prop] = item[prop]; } } return acc; }, {}); console.log(sumProps); var totalSum = 0; for (item in sumProps) { totalSum += sumProps[item]; } console.log(totalSum);

好吧,我写了一个名为total()的 function 来完成你想要的。

我将属性名称和源数组传递给total() ,它返回一个新的 object 命名总计,例如total( array, ['property1','property2'])给我{ "property1": 77, "property2": 42 }

但是,由于我认为您希望学习,而不仅仅是获得答案,因此我建议您阅读有关Array.reduce()Array.map()Object.fromEntries()的内容。

您可以在下面看到我使用这些解决问题的方式。 一旦您阅读了这些功能,我希望我的回答是有意义的。 (使用这些数组函数具有挑战性,所以请耐心尝试掌握它们。)

const testJSON = {
    "property1": [{
            "id": "abc",
            "category": "recordsCount1"
        }, {
            "id": "def",
            "category": "recordsCount2"
        }
    ],
    "property2": [{
            "abc": 8,
            "def": 15
        }, {
            "abc": 62,
            "def": 7
        }, {
            "abc": 4,
            "def": 16
        }
    ]
}

function total( array, properties ) {

    const entries = properties.map(
        propertyName => [
            propertyName,
            array.reduce( 
                ( sum, entry ) => sum + entry[ propertyName ], 
                0 
            )
        ]
    );

    return Object.fromEntries( entries );

}

console.log( total( testJSON.property2, [ 'abc', 'def' ] ) );

暂无
暂无

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

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