I have an array like this
data = [
{ name : "sa", attributes : [{skin : "green"},{nose:"good"}]},
{ name : "sa", attributes : [{skin : "red"},{nose:"bad"}]},
{ name : "sa", attributes : [{skin : "green"},{nose:"good"}]},
{ name : "sa", attributes : [{nose:"good}]},
]
so i want the grouping of array based on skin attribute. I am using _ underscore library like this
const attributeType = "skin";
const groupedCollections = _.groupBy(colls, (col) => {
const data = col.attributes.find((attribute) => {
const keys = Object.keys(attribute);
return keys.indexOf(attributeType) > -1 ? true : false
});
return data?.value
});
but this is making grouping under undefined
.
Any help?
CodePudding user response:
You need to return the value of the wanted property.
const
colls = [{ name: "sa", attributes: [{ skin: "green" }, { nose: "good" }] }, { name: "sa", attributes: [{ skin: "red" }, { nose: "bad" }] }, { name: "sa", attributes: [{ skin: "green" }, { nose: "good" }] }, { name: "sa", attributes: [{ nose: "good" }] }],
attributeType = "skin",
groupedCollections = _.groupBy(colls, ({ attributes }) => attributes
.find(attribute => attributeType in attribute)
?.[attributeType]
);
console.log(groupedCollections);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>