0👍
You could do something like:
let input = [
{
title: 'Title 1',
id: '1',
categories: ['food']
},
{
title: 'Title 2',
id: '2',
categories: ['cat']
},
{
title: 'Title 3',
id: '3',
categories: ['food', 'cat']
},
{
title: 'Title 4',
id: '4',
categories: ['sky']
},
{
title: 'Title 5',
id: '5',
categories: ['cat', 'sky']
},
];
function findTitles(category) {
let result = [];
input.forEach(val => {
if (val.categories.includes(category)) result.push(val.title);
})
return result;
}
console.log(findTitles("food"))
I’m returning an array of titles passing the category to findTitles
. findTitles
function iterates on input array finding a categories
that contains the category.
EDIT: This is the version with all categories:
let input = [
{
title: 'Title 1',
id: '1',
categories: ['food']
},
{
title: 'Title 2',
id: '2',
categories: ['cat']
},
{
title: 'Title 3',
id: '3',
categories: ['food', 'cat']
},
{
title: 'Title 4',
id: '4',
categories: ['sky']
},
{
title: 'Title 5',
id: '5',
categories: ['cat', 'sky']
},
];
function findTitles(categories) {
let result = [];
for (let i = 0; i < categories.length; i++){
let resultObj = {};
resultObj.category = categories[i];
resultObj.items = [];
input.forEach(val => {
if (val.categories.includes(categories[i])) {
resultObj.items.push({"title": val.title, "id": val.id});
}
})
result.push(resultObj);
}
return result;
}
console.log(findTitles(['food', 'cat', 'sky']))
0👍
Working DEMO:
var myArr = [
{
title: 'Title 1',
id: '1',
categories: ['food']
},
{
title: 'Title 2',
id: '2',
categories: ['cat']
},
{
title: 'Title 3',
id: '3',
categories: ['food', 'cat']
},
{
title: 'Title 4',
id: '4',
categories: ['sky']
},
{
title: 'Title 5',
id: '5',
categories: ['cat', 'sky']
},
];
function myFun(arr) {
var uniqueCats = [];
var catsObj = {};
var finalArr = [];
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
var cats = item.categories;
var title = item.title;
var id = item.id;
for (var j = 0; j < cats.length; j++) {
var cat = cats[j];
if (uniqueCats.indexOf(cat) < 0) {
uniqueCats.push(cat); //console.log(uniqueCats);
catsObj[cat] = [];
}
catsObj[cat].push({
'title': title,
'id': id
});
}
}
for(var key in catsObj) {
finalArr.push({
"category": key,
"items": catsObj[key]
});
}
return finalArr;
}
console.log(myFun(myArr));
- [Vuejs]-Vue Component control Component instance variable by another same Component
- [Vuejs]-How do I get my images to load in Vue app using webpack and vue-loader?
Source:stackexchange.com