javascript - JS Object transformation based on values of object properties -
i've seen lots of other questions related js object sorting, of tend suggest using .map method sort object or array of objects based on value of property, i'm trying achieve different.
i'm trying turn object format:
{ "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" } ] }
into object formatted using value of 'repository' this:
{ "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" } ] }
so need original object, object array of other objects, return object contains numerous arrays, named after values of repository property , containing each object matches property value.
use array#foreach
method
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 pproperty if not defined res[v.repository] = res[v.repository] || []; // push reference object or recreate depense on need res[v.repository].push(v); }) console.log(res);
or using array#reduce
method
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 object obj[v.repository].push(v); // return result object return obj; }, {}) console.log(res);
Comments
Post a Comment