假设我有一个看起来像这样的对象:
{
"data": {
"postsConnection": {
"groupBy": {
"author": [
{
"key": "xyz",
"connection": {
"aggregate": {
"count": 5
}
}
},
{
"key": "abc",
"connection": {
"aggregate": {
"count": 3
}
}
}
]
}
}
}
}
如何访问count
对应于author
具有xyz
键的元素的值?我知道对于这个特定的例子,我可以这样做:
const n = data.postsConnection.groupBy.author[0].connection.aggregate.count
但这意味着提前知道数组中的哪个元素保存 的所需值key
,而在我的上下文中并非如此。
如果作者可以多次出现,则可以.filter()
将数组存储在author
,然后.map()
将结果发送到count
:
const data = {data:{postsConnection:{groupBy:{author:[{key:"xyz",connection:{aggregate:{count:5}}},{key:"abc",connection:{aggregate:{count:3}}}]}}}};
const author = "xyz";
const res = data.data.postsConnection.groupBy.author.filter(({key}) => key === author).map(obj => obj.connection.aggregate.count);
console.log(res);
// If you want to get the total of all counts for the given author, you can use reduce on the result to sum:
const totalCountsForAuthor = res.reduce((acc, n) => acc+n, 0);
console.log(totalCountsForAuthor);
如果作者只能出现一次,你可以使用.find()
代替.filter()
像这样:
const data = {data:{postsConnection:{groupBy:{author:[{key:"xyz",connection:{aggregate:{count:5}}},{key:"abc",connection:{aggregate:{count:3}}}]}}}};
const author = "xyz";
const res = data.data.postsConnection.groupBy.author.find(({key}) => key === author).connection.aggregate.count
console.log(res);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句