说我有一个看起来像这样的对象:
{
"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
的期望值,在我的上下文中情况并非如此。
答案 0 :(得分:2)
如果作者可以出现多次,则可以.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);
答案 1 :(得分:1)
您可以使用Array#find
获取满足特定条件的数组中的第一个实例(在您的情况下,您的key
值等于key
值的第一个实例)想要)。
var obj = {"data":{"postsConnection":{"groupBy":{"author":[{"key":"xyz","connection":{"aggregate":{"count":5}}},{"key":"abc","connection":{"aggregate":{"count":3}}}]}}}};
function getAuthorByKey(key) {
return obj.data.postsConnection.groupBy.author.find(author => author.key === key);
}
console.log(getAuthorByKey("xyz").connection.aggregate.count);
console.log(getAuthorByKey("abc").connection.aggregate.count);
答案 2 :(得分:1)
如果author
数组始终存在:
const data = {
postsConnection: {
groupBy: {
author: [{
key: "xyz",
connection: {
aggregate: {
count: 5
}
}
}, {
key: "abc",
connection: {
aggregate: {
count: 3
}
}
}]
}
}
};
function getCount(keyVal) {
const element = data.postsConnection.groupBy.author.find(item => item.key === keyVal)
return element.connection.aggregate.count || "";
}
console.log(getCount('xyz'))
答案 3 :(得分:1)
var data = { "data": {
"postsConnection": {
"groupBy": {
"author": [
{
"key": "xyz",
"connection": {
"aggregate": {
"count": 5
}
}
},
{
"key": "abc",
"connection": {
"aggregate": {
"count": 3
}
}
}
]
}
}
}
};
data.data.postsConnection.groupBy.author.forEach((autor) => {
if(autor.key === "xyz")
console.log(autor.connection.aggregate);
});
答案 4 :(得分:1)
您可以利用数组查找,通过“键”查找作者。
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
const author = data.postsConnection.groupBy.author.find((author) => author.key === "xyz")
CodePen: https://codepen.io/gmaslic/pen/wvwbLoL
然后,您可以访问找到的“作者”中的所有属性