arrays - Javascript combining two objects into new object with unique data element i.e. year -


i have following 2 objects in js year unique in both objects. want combine them new object year same.

var financials = [{"year": 2013, "rev_prod1": 10000, "rev_prod2": 5000}, {"year": 2014, "rev_prod1": 8000, "rev_prod2": 10000}, {"year": 2015, "rev_prod1": 15000, "rev_prod2": 20000}]  var stats = [{"year": 2013, "units_sold": 900, "hours": 55},{"year": 2014, "units_sold": 800, "hours": 45}, {"year": 2015, "units_sold": 1000, "hours": 70}] 

the expected output this:

var combineddata = [{"year": 2013, "rev_prod1": 10000, "rev_prod2": 5000, "units_sold": 900, "hours": 55}, {"year": 2014, "rev_prod1": 8000, "rev_prod2": 10000, "units_sold": 800, "hours": 45}, {"year": 2015, "rev_prod1": 15000, "rev_prod2": 20000, "units_sold": 1000, "hours": 70}] 

you use hash table stats objects , merge values iterating keys.

var financials = [{ "year": 2013, "rev_prod1": 10000, "rev_prod2": 5000 }, { "year": 2014, "rev_prod1": 8000, "rev_prod2": 10000 }, { "year": 2015, "rev_prod1": 15000, "rev_prod2": 20000 }],      stats = [{ "year": 2013, "units_sold": 900, "hours": 55 }, { "year": 2014, "units_sold": 800, "hours": 45 }, { "year": 2015, "units_sold": 1000, "hours": 70 }],      hash = object.create(null);    stats.foreach(function (o) {      hash[o.year] = o;  });    financials.foreach(function (o) {      object.keys(hash[o.year]).foreach(function (k) {          o[k] = hash[o.year][k];      });  });    console.log(financials);
.as-console-wrapper { max-height: 100% !important; top: 0; }

es6 map , object.assign.

var financials = [{ "year": 2013, "rev_prod1": 10000, "rev_prod2": 5000 }, { "year": 2014, "rev_prod1": 8000, "rev_prod2": 10000 }, { "year": 2015, "rev_prod1": 15000, "rev_prod2": 20000 }],      stats = [{ "year": 2013, "units_sold": 900, "hours": 55 }, { "year": 2014, "units_sold": 800, "hours": 45 }, { "year": 2015, "units_sold": 1000, "hours": 70 }],      map = new map(stats.map(o => [o.year, o]));    financials.foreach(o => object.assign(o, map.get(o.year)));    console.log(financials);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -