Reputation: 576
I am having a JSON array:
{
"assets": [
{
"extension": "png",
"id": "3",
"fileType": "IMG",
"name": "Screenshot-2020-07-09-at-4-25-30-PM_XX"
},
{
"extension": "jpg",
"id": "10",
"fileType": "IMG",
"name": "vertical-1_XXX"
},
{
"extension": "mp4",
"id": "15",
"fileType": "VID",
"name": "aaa"
},
{
"extension": "pdf",
"id": "19",
"fileType": "DOC",
"name": "ccc"
}
]
}
I need to group by filetype say for example for filetype IMG only 2
[
{
"extension": "png",
"id": "3",
"fileType": "IMG",
"name": "Screenshot-2020-07-09-at-4-25-30-PM_XX"
},
{
"extension": "jpg",
"id": "10",
"fileType": "IMG",
"name": "vertical-1_XXX"
}]
likewise, for the other 2 filetypes, the length of the array will be 1, since it has each element in the array
Please help me to groupb
y fileType in react
Upvotes: 0
Views: 723
Reputation: 5098
Working Code !!
using map()
method in ES6
const data = {
"assets": [{
"extension": "png",
"id": "3",
"fileType": "IMG",
"name": "Screenshot-2020-07-09-at-4-25-30-PM_XX"
},
{
"extension": "jpg",
"id": "10",
"fileType": "IMG",
"name": "vertical-1_XXX"
},
{
"extension": "mp4",
"id": "15",
"fileType": "VID",
"name": "aaa"
},
{
"extension": "pdf",
"id": "19",
"fileType": "DOC",
"name": "ccc"
}
]
};
const filterFile = (type) => {
let result = [];
data.assets.map((o) => {
if (o.fileType === type) {
result = [...result, o];
}
});
return result;
}
console.log(filterFile('IMG'));
Upvotes: 1
Reputation: 5205
I guess this is what you want to do. Use .reduce
to group the elements based on their filetype.
var arr = {
"assets": [
{
"extension": "png",
"id": "3",
"fileType": "IMG",
"name": "Screenshot-2020-07-09-at-4-25-30-PM_XX"
},
{
"extension": "jpg",
"id": "10",
"fileType": "IMG",
"name": "vertical-1_XXX"
},
{
"extension": "mp4",
"id": "15",
"fileType": "VID",
"name": "aaa"
},
{
"extension": "pdf",
"id": "19",
"fileType": "DOC",
"name": "ccc"
}
]
};
var data = arr.assets;
var r= data.reduce((acc, ele)=>{
acc[ele.fileType] = acc[ele.fileType] ? [...acc[ele.fileType], ele] : [ele];
return acc
},{});
console.log(r['IMG'])
EDIT:
To get only IMG
grouping you can just do r['IMG']
Upvotes: 1
Reputation: 3502
Hope this is what You are looking for :
var testObj = {
"assets": [
{
"extension": "png",
"id": "3",
"fileType": "IMG",
"name": "Screenshot-2020-07-09-at-4-25-30-PM_XX"
},
{
"extension": "jpg",
"id": "10",
"fileType": "IMG",
"name": "vertical-1_XXX"
},
{
"extension": "mp4",
"id": "15",
"fileType": "VID",
"name": "aaa"
},
{
"extension": "pdf",
"id": "19",
"fileType": "DOC",
"name": "ccc"
}
]
}
const groupBy = function(toFilter,type){
let res = testObj.assets.filter(obj=>obj[toFilter]===type);
return res;
}
console.log(groupBy('fileType',"IMG"));
//LIKE WISE PASS ON THE toFilter , and type
Upvotes: 1