1

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?

1
  • What about using keys.includes instead of keys.indexOf? Commented Feb 25, 2022 at 16:55

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.