简体   繁体   中英

Extract 1 of each property from object

I am looking for a method using lodash/underscore(or plain JS if one does not exist) that will only me to take a given object such as below.

animals: {
  {
    type: 'duck',
    name: 'quack',
  },
  {
    type: 'duck',
    name: 'quieck',
  },
  {
    type: 'dog',
    name: 'bark',
  },
},

This object for example contains 3 different animals, but two of them are the same type.

The end result is to be able to use a control structure such as a for loop to iterate through each TYPE of animal, such that I'm working with something that only has one instance of each type.

This is being used because I am creating a list.

This list will be similar to the following

duck
 name is quack
 name is quick
dog
 name is bark

But i want to do this with control structures and not by simply outputting and hardcoding in each name, as this list will get very extensive and long.

I would use the uniq function.

var uniqueAnimals = _.uniq(animals, function(item, key, type) { 
    return item.type;
});

Presuming animals is not a syntax error, but an array: If you don't just want to filter the unique types but also create a structure for your output, you could go with an object:

var kv = {};
animals.forEach(function(a) {
    if(kv[a.type]) {
        kv[a.type].push(a.name);
    } else {
        kv[a.type] = [];
    } 
}

Later, you could iterate Object.keys(kv) to print your key/values

_.groupBy() maybe?

 var animals = [ { type: 'duck', name: 'quack', }, { type: 'duck', name: 'quieck', }, { type: 'dog', name: 'bark', }, ]; var grouped = _.groupBy(animals, 'type'); document.write('<pre>' + JSON.stringify(grouped, null, 3) + '</pre>'); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM