2016-06-11 2 views
-1

jsオブジェクトのソートに関連する他の多くの質問がありました。そのほとんどは、.mapメソッドを使用してオブジェクトまたはオブジェクトの配列を値に基づいてソートすることを推奨しがちですプロパティが、私は少し異なるものを達成しようとしています。オブジェクトプロパティの値に基づくJSオブジェクトの変換

私は、このオブジェクトのフォーマットターンしようとしています:

{ 
    "example-repo-1": [ 
     { 
      "repository": "example-repo-1", 
      "commit_hash": "example-hash-1" 
     }, 
     { 
      "repository": "example-repo-1", 
      "commit_hash": "example-hash-1.2" 
     } 
    ], 
    "example-repo-2": [  
     { 
      "repository": "example-repo-2", 
      "commit_hash": "example-hash-2" 
     } 
    ] 
} 

は、だから私は私の元のオブジェクトを取得する必要があります。このような「リポジトリ」の値を使用してフォーマットされたオブジェクトに

{ 
    "commits": [ 
     { 
      "repository": "example-repo-1", 
      "commit_hash": "example-hash-1" 
     }, 
     { 
      "repository": "example-repo-1", 
      "commit_hash": "example-hash-1.2" 
     }, 
     { 
      "repository": "example-repo-2", 
      "commit_hash": "example-hash-2" 
     } 
    ] 
} 

をこれは、リポジトリプロパティの値の後に名前が付けられ、そのプロパティ値に一致する各オブジェクトを含む多数の配列を含むオブジェクトを返すために、他のオブジェクトの配列を持つオブジェクトです。

答えて

2

使用Array#forEach方法

var data = { 
 
    "commits": [{ 
 
    "repository": "example-repo-1", 
 
    "commit_hash": "example-hash-1" 
 
    }, { 
 
    "repository": "example-repo-1", 
 
    "commit_hash": "example-hash-1.2" 
 
    }, { 
 
    "repository": "example-repo-2", 
 
    "commit_hash": "example-hash-2" 
 
    }] 
 
}; 
 

 
var res = {}; 
 

 
data.commits.forEach(function(v) { 
 
    // define the pproperty if already not defined 
 
    res[v.repository] = res[v.repository] || []; 
 
    // push the reference to the object or recreate depense on your need 
 
    res[v.repository].push(v); 
 
}) 
 

 
console.log(res);


又は使用Array#reduce方法

var data = { 
 
    "commits": [{ 
 
    "repository": "example-repo-1", 
 
    "commit_hash": "example-hash-1" 
 
    }, { 
 
    "repository": "example-repo-1", 
 
    "commit_hash": "example-hash-1.2" 
 
    }, { 
 
    "repository": "example-repo-2", 
 
    "commit_hash": "example-hash-2" 
 
    }] 
 
}; 
 

 
var res = data.commits.reduce(function(obj, v) { 
 
    // define property if not defined 
 
    obj[v.repository] = obj[v.repository] || []; 
 
    // push the object 
 
    obj[v.repository].push(v); 
 
    // return the result object 
 
    return obj; 
 
}, {}) 
 

 
console.log(res);

-1

この

var input = { 
 
    "commits": [ 
 
     { 
 
      "repository": "example-repo-1", 
 
      "commit_hash": "example-hash-1" 
 
     }, 
 
     { 
 
      "repository": "example-repo-1", 
 
      "commit_hash": "example-hash-1.2" 
 
     }, 
 
     { 
 
      "repository": "example-repo-2", 
 
      "commit_hash": "example-hash-2" 
 
     } 
 
    ] 
 
}; 
 

 
var output = {}; 
 

 
input.commits.forEach(function(el){ 
 
    if(!output[el.repository]) 
 
    output[el.repository] = []; 
 
    output[el.repository].push[el]; 
 
    }) 
 
console.log(output);

のようなものを試してみてください
関連する問題