简体   繁体   中英

How to filter through objects to get Result from Given (javascript)

I need to taken what is given and print the result. How do I filter through the animals object to get the result object?

Given:

var animals = [
  { type: 'monkey', owner: 'Callie' },
  { type: 'rat', owner: 'Johnnie' },
  { type: 'rat', owner: 'Callie' },
  { type: 'monkey', owner: 'Megan' },
  { type: 'rat', owner: 'Megan' },
  { type: 'horse', owner: 'Megan' }
];

Result:

[
  { type: 'rat', owner: [ 'Johnnie', 'Callie', 'Megan' ], count: 3 },
  { type: 'monkey', owner: [ 'Megan', 'Callie' ], count: 2 },
  { type: 'horse', owner: [ 'Megan' ], count: 1 } 
]; 

My code is:

endorsements.map( function(endorsement){
    var hash = {}, users = [], count = 0, result = [], skills = endorsement.skill, skill; 

        for(var i = 0; i < skills.length; i++){
            skill = skills[i]; 
            if(!hash[skill]){
              result.push(skill); hash[skill] = true; count++; users.push(endorsement.user); 
            } 
        } 
    return {skill: skill, user: users, count: count};
 });

You can reduce the animals array and then take the values of the result's object:

 var animals = [ { type: 'monkey', owner: 'Callie' }, { type: 'rat', owner: 'Johnnie' }, { type: 'rat', owner: 'Callie' }, { type: 'monkey', owner: 'Megan' }, { type: 'rat', owner: 'Megan' }, { type: 'horse', owner: 'Megan' } ]; var res = Object.values(animals.reduce(function(all, item) { if (!all.hasOwnProperty(item.type)) { all[item.type] = {type: item.type, owner: [], count: 0} } all[item.type]['owner'].push(item.owner); all[item.type]['count']++; return all; }, {})); console.log(res); 

I might suggest a different result format. If you really need the format you suggest, I think getting what I suggest as an intermediate step would make it easy.

My suggested format:

{
  rat: ['Johnnie', 'Callie', 'Megan'],
  monkey: ['Megan', 'Callie'],
  horse: ['Megan']
}

To build this format:

var animals = [
  { type: 'monkey', owner: 'Callie' },
  { type: 'rat', owner: 'Johnnie' },
  { type: 'rat', owner: 'Callie' },
  { type: 'monkey', owner: 'Megan' },
  { type: 'rat', owner: 'Megan' },
  { type: 'horse', owner: 'Megan' }
];

var result = {};
for (var idx = 0; idx < animals.length; idx++) {
  if (!result[animals[idx].type]) {
    result[animals[idx].type] = [];
  }
  result[animals[idx].type].push(animals[idx].owner);
}

// get some info
result['rat'].length; // 3 people own a rat
result['monkey'].indexOf('Megan'); // 1 since Megan owns a monkey
Object.keys(result); // ['rat', 'monkey', 'horse']

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