2016-12-01 38 views
3

这是一个数据结构类型的问题,所以我认为这将是一个很好的论坛来问问它。 我开始遇到以下相当多的问题。 某些服务以下列格式向我发送数据。 这是一群人,告诉我他们拥有什么宠物。JavaScript - 重构对象列表的工具?

owners = [ 
    { 
    owner: 'anne', 
    pets: ['ant', 'bat'] 
    }, 
    { 
    owner: 'bill', 
    pets: ['bat', 'cat'] 
    }, 
    { 
    owner: 'cody', 
    pets: ['cat', 'ant'] 
    } 
]; 

但我真正想要的,是宠物的数组,这人有他们,就像这样:

pets = [ 
    { 
    pet: 'ant', 
    owners: ['anne', 'cody'] 
    }, 
    { 
    pet: 'bat', 
    owners: ['anne', 'bill'] 
    }, 
    { 
    pet: 'cat', 
    owners: ['bill', 'cody'] 
    } 
]; 

有一些工具,我可以说,“改变我输入数组一个独特的宠物对象数组,其中每个输出对象都有一个属性,其值是一组所有者?“

还是我需要手工写这个吗?

回答

1

你可以在哈希表的帮助下建立一个新的数组,并迭代所有的所有者和所有的宠物。

var owners = [{ owner: 'anne', pets: ['ant', 'bat'] }, { owner: 'bill', pets: ['bat', 'cat'] }, { owner: 'cody', pets: ['cat', 'ant'] }], 
 
    pets = []; 
 

 
owners.forEach(function (owner) { 
 
    owner.pets.forEach(function (pet) { 
 
     if (!this[pet]) { 
 
      this[pet] = { pet: pet, owners: [] } 
 
      pets.push(this[pet]); 
 
     } 
 
     this[pet].owners.push(owner.owner); 
 
    }, this) 
 
}, Object.create(null)); 
 

 
console.log(pets);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

使用Array.prototype.reducehash table的溶液 - 见下面演示:

var owners=[{owner:'anne',pets:['ant','bat']},{owner:'bill',pets:['bat','cat']},{owner:'cody',pets:['cat','ant']}]; 
 

 
var pets = owners.reduce(function(hash) { 
 
    return function(p,c){ 
 
    c.pets.forEach(function(e){ 
 
     hash[e] = hash[e] || []; 
 
     if(hash[e].length === 0) 
 
     p.push({pet:e,owners:hash[e]}); 
 
     hash[e].push(c.owner); 
 
    }); 
 
    return p; 
 
    } 
 
}(Object.create(null)), []); 
 

 
console.log(pets);
.as-console-wrapper{top:0;max-height:100%!important;}