Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two arrays into an array of objects with property values

Tags:

javascript

Need to generate a JSON as below:

{ applicationName :'appName1', frequency:'00'},
{ applicationName :'appName2', frequency:'3'},
{ applicationName :'appName3', frequency:'25'},
{ applicationName :'appName4', frequency:'54'}

scope.appApplications - its a JSON object that I am splitting into two arrays. I have two arrays as below. Need to merge them(applicationName[] and frequencies[]) and come with output as above. How can this be done?

var frequencies = [];
var applicationName = [];
angular.forEach(scope.appApplications, function (value, key) {
           frequencies.push(value);
           applications.push(key);
 })
like image 434
Avs_90 Avatar asked Feb 10 '23 08:02

Avs_90


2 Answers

If you're willing to use underscore, you can do this as a single chained functional call:

_.zip(applicationName,frequencies).map(function(pair) { 
    return _.object(["applicationName","frequency"],pair); 
});

_.zip() turns ['a','b','c'] and [1,2,3] into [['a',1],['b',2],['c',3]].

Array.map() calls a function on each member of an array and returns an array of the results.

_.object() turns ["applicationName","frequency"] and ['a',1] into {applicationName: 'a', frequency: 1}.

like image 134
S McCrohan Avatar answered Feb 12 '23 20:02

S McCrohan


You can have an another variable (say targetJson) which will hold your target json. something like this.

var frequencies = [];
var applicationName = [];
var targetJson = [];
angular.forEach(scope.appApplications, function (value, key) {
           frequencies.push(value);
           applications.push(key);
           targetJson.push({applicationName :key, frequency:value});
 })
like image 23
Sameer Azazi Avatar answered Feb 12 '23 21:02

Sameer Azazi