18.05.2021, 08:53
|
Интересующийся
|
|
Регистрация: 05.11.2020
Сообщений: 22
|
|
массив с глубокой вложенностью объектов
Нужно вернуть количество comments и post автора. Как посчитать количество comments ?
const getQuantityPostsByAuthor = (listOfPosts, authorName) => {
let att = 0;
let com = 0;
listOfPosts.forEach(function (arrayItem) {
if (arrayItem.author === authorName) {
att += 1;
}
if (arrayItem.comments.author === authorName) {//попытка вернуть количество comment ;
com += 1;
}
});
return `Post:${att},comments:${com}` //`Post:${att} ,comments:${com}`;
};
let listOfPosts2 = [
{
id: 1,
post: 'some post1',
title: 'title 1',
author: 'Ivanov',
comments: [
{
id: 1.1,
comment: 'some comment1',
title: 'title 1',
author: 'Rimus'
},
{
id: 1.2,
comment: 'some comment2',
title: 'title 2',
author: 'Uncle'
}
]
},
{
id: 2,
post: 'some post2',
title: 'title 2',
author: 'Ivanov',
comments: [
{
id: 1.1,
comment: 'some comment1',
title: 'title 1',
author: 'Rimus'
},
{
id: 1.2,
comment: 'some comment2',
title: 'title 2',
author: 'Uncle'
},
{
id: 1.3,
comment: 'some comment3',
title: 'title 3',
author: 'Rimus'
}
]
},
{
id: 3,
post: 'some post3',
title: 'title 3',
author: 'Rimus'
},
{
id: 4,
post: 'some post4',
title: 'title 4',
author: 'Uncle'
}
];
console.log(getQuantityPostsByAuthor(listOfPosts2, 'Rimus'));
|
|
18.05.2021, 10:12
|
|
Профессор
|
|
Регистрация: 27.05.2010
Сообщений: 33,121
|
|
OlesiaBOM,
const getQuantityPostsByAuthor = (listOfPosts, authorName) => {
let att = 0;
let com = 0;
listOfPosts.forEach(({ author, comments }) => {
att += author === authorName;
if (comments) com += comments.filter(({ author }) => author === authorName).length
})
return `Post: ${att}, comments: ${com}`
};
let listOfPosts2 = [{
id: 1,
post: 'some post1',
title: 'title 1',
author: 'Ivanov',
comments: [{
id: 1.1,
comment: 'some comment1',
title: 'title 1',
author: 'Rimus'
},
{
id: 1.2,
comment: 'some comment2',
title: 'title 2',
author: 'Uncle'
}
]
},
{
id: 2,
post: 'some post2',
title: 'title 2',
author: 'Ivanov',
comments: [{
id: 1.1,
comment: 'some comment1',
title: 'title 1',
author: 'Rimus'
},
{
id: 1.2,
comment: 'some comment2',
title: 'title 2',
author: 'Uncle'
},
{
id: 1.3,
comment: 'some comment3',
title: 'title 3',
author: 'Rimus'
}
]
},
{
id: 3,
post: 'some post3',
title: 'title 3',
author: 'Rimus'
},
{
id: 4,
post: 'some post4',
title: 'title 4',
author: 'Uncle'
}
];
console.log(getQuantityPostsByAuthor(listOfPosts2, 'Rimus'));
|
|
18.05.2021, 10:39
|
Интересующийся
|
|
Регистрация: 05.11.2020
Сообщений: 22
|
|
Спасибо.
|
|
|
|