0

I have an object like this

data: [
  {
    "Type":"100, S4",
    "Model":"1 serie, e82",
    "Manufacturer":"BMW",
    "Vehicle":"Cars"
  },
  {
    "Type":"type 2",
    "Model":"a serie",
    "Manufacturer":"Toyota",
    "Vehicle":"Cars"
  },
  {
    "Type":"type 3",
    "Model":"v4",
    "Manufacturer":"Toyota",
    "Vehicle":"SUVs"
  }
]

then I used jquery and lodash library with expect to return distinct value from the object.

Tried #1:

  $.each( data, function( i, value ) {
    var vehicles = _.uniqBy(value);
    console.log(vehicles);
  });

Result: got 3 empty arrays printed in console.log

Tried #2:

  $.each( data, function( i, value ) {
    var vehicles = _.uniqBy(value.Vehicle);
    console.log(vehicles);
  });

Result: 4 arrays within split characters

(4) ["C", "a", "r", "s"]
(4) ["C", "a", "r", "s"]
(4) ["S", "U", "V", "s"]

I expected to got an array within

["Cars", "SUVs"]

How could I deal with it? Thanks for help!

2 Answers 2

1

You can use lodash#map to get all Vehicle property strings, and then use lodash#uniq to remove all duplicate strings.

var result = _(data).map('Vehicle').uniq().value();

var data = [
  {
    "Type":"100, S4",
    "Model":"1 serie, e82",
    "Manufacturer":"BMW",
    "Vehicle":"Cars"
  },
  {
    "Type":"type 2",
    "Model":"a serie",
    "Manufacturer":"Toyota",
    "Vehicle":"Cars"
  },
  {
    "Type":"type 3",
    "Model":"v4",
    "Manufacturer":"Toyota",
    "Vehicle":"SUVs"
  }
];

var result = _(data).map('Vehicle').uniq().value();

console.log(result);
body > div { top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

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

Comments

1

Try this

var vehicles  = _.uniqBy(data, function (e) {
      return e.Vehicle;
    }).map(function(veh){
    return veh.Vehicle;
});   
console.log(vehicles);

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.