如何过滤对象以获取给定的结果(javascript)

时间:2017-09-12 22:02:40

标签: javascript object filter

我需要采取给定的内容并打印结果。如何过滤animals对象以获取结果对象?

假设:

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' }
];

结果:

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

我的代码是:

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};
 });

2 个答案:

答案 0 :(得分:0)

您可以reduce animals数组,然后获取结果对象的values

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);

答案 1 :(得分:0)

我可能会建议使用不同的结果格式。如果你真的需要你建议的格式,我认为得到我建议的中间步骤会让事情变得简单。

我建议的格式:

[i-081ec3ffa72eb338, i-0c7474fb67bb9043]

构建此格式:

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