0

I have a collection of objects

var array = 
[
    {"category":"A", "categoryname":"somename", key: 1, description: "something"}, 
    {"category":"A", "categoryname":"somename", key: 1, description: "something"}, 
    {"category":"B", "categoryname": "somename", key: 1, description: "something"}
    {"category":"B", "categoryname": "somename", key: 3, description: "something"}
    {"category":"C", "categoryname": "somename", key: 2, description: "something"}
    {"category":"C", "categoryname": "somename", key: 2, description: "something"}
]

that have 4 values (category, categoryname, key, description) and I need to loop through it and get a unique list of objects based on the category. But I want to return the unique list with 2 preoperties and not just one. If I use

_.uniq(_.pluck(array,"category"))

this gives me what I want except I need the categoryname as well as the category. Is this possible?

2
  • What is expected result? Commented Oct 10, 2016 at 23:35
  • [ ["A", "somename"],["B","somename"],["C","somename"] ] Commented Oct 10, 2016 at 23:41

2 Answers 2

2

There are a couple of questions on the same use case already.

Plucking Multiple Properties

Removing duplicate objects with Underscore for Javascript

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

Comments

-1

You can use $.unique(), Array.prototype.map(), JSON.stringify(), JSON.parse()

var array = [{
  "category": "A",
  "categoryname": "somename",
  key: 1,
  description: "something"
}, {
  "category": "A",
  "categoryname": "somename",
  key: 1,
  description: "something"
}, {
  "category": "B",
  "categoryname": "somename",
  key: 1,
  description: "something"
}, {
  "category": "B",
  "categoryname": "somename",
  key: 3,
  description: "something"
}, {
  "category": "C",
  "categoryname": "somename",
  key: 2,
  description: "something"
}, {
  "category": "C",
  "categoryname": "somename",
  key: 2,
  description: "something"
}];

var res = $.unique(array.map(function(el) {
  return JSON.stringify([el.category, el.categoryname])
})).map(JSON.parse);

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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.