如何计算数组中的值数?

编程入门 行业动态 更新时间:2024-10-21 16:26:37
本文介绍了如何计算数组中的值数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试计算json数组的值.

I am trying to count the values a json array.

如果"beta = b",我想计算"sierra"数据数组中id的数量.因此,请对照设置为值"b"的环境变量("B")检查data [].beta的值.

I want to count the number of id's in the data array of "sierra" if "beta = b". Hence checking the value of data[].beta against the environment variable ("B") set to value 'b'.

这里的问题是我在每次数据迭代中都没有塞拉利昂" [].

The issue here is I do not have "sierra" in every iteration of data[].

{ "data": [{ "alpha": "a", "beta": "b", "delta": { "cat": "dog" }, "gamma": { "sierra": { "data": [ { "type": "alphabet", "id": "a" }, { "type": "alphabet", "id": "b" } ] } } }, { "alpha": "a", "beta": "b", "delta": { "cat": "dog" }, "bravo": { "data": [ { "type": "number", "id": "1" }, { "type": "number", "id": "2" } ] } } }, { "alpha": "x", "beta": "y", "delta": { "cat": "dog" }, "gamma": { "sierra": { "data": [ { "type": "alphabet", "id": "c" }, { "type": "alphabet", "id": "d" } ] } } }] }

上面的json是我在邮递员中看到的响应正文. 循环"是我的"for"循环的计数.

Above json is the response body I see in postman. "loop" is the count of my "for" loop.

我已经尝试过了:

1. pm.response.json().data[loop].gamma.sierra.data().id).size() 2. for(var loop =0; loop < pm.response.json().data.length; loop++) { if(pm.response.json().data[loop].beta===pm.variables.get("B")) { pm.response.json().data.map((item, loop) => { if(item.gamma){ // check if gamma key is present console.log(item.gamma.sierra.filter(data =>data.id ).length); // } }); result=true; break; } } pm.expect(true).to.eql(result);

预期:2

Actual: TypeError: Cannot read property 'sierra' of undefined Actual: item.relationships.apps.filter is not a function

推荐答案

您可以采用动态方法,将要计算特定内部键的对象的键移交.

You could take a dynamic apporach and hand over the key of the object where you like to count a certain inner key.

function count(object, key, subKey) { const noObject = o => !o || typeof o !== 'object'; function subCount(object) { if (noObject(object)) return 0; if (subKey in object) return 1; return Object.values(object).reduce((s, o) => s + subCount(o), 0); } if (noObject(object)) return 0; if (key in object) return subCount(object[key]); return Object.values(object).reduce((s, o) => s + count(o, key, subKey), 0); } var data = { data: [{ alpha: "a", beta: "b", delta: { cat: "dog" }, gamma: { sierra: { data: [{ type: "alphabet", id: "a" }, { type: "alphabet", id: "b" }] } } }] }; console.log(count(data, 'sierra', 'id')); // 2

更多推荐

如何计算数组中的值数?

本文发布于:2023-11-22 13:50:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617681.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!