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);
})
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}
.
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});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With