2016-12-01 7 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;}

関連する問題