Combining two arrays into an array of objects with property values
JSON needs to be generated as shown below:
{ applicationName :'appName1', frequency:'00'},
{ applicationName :'appName2', frequency:'3'},
{ applicationName :'appName3', frequency:'25'},
{ applicationName :'appName4', frequency:'54'}
scope.appApplications is a JSON object that I split into two arrays. I have two arrays as shown below. You need to combine them (applicationName [] and frequencies []) and come up with an output as above. How can I do that?
var frequencies = [];
var applicationName = [];
angular.forEach(scope.appApplications, function (value, key) {
frequencies.push(value);
applications.push(key);
})
source to share
Assuming scope.appApplications
is an object where keys are application names and values are frequencies, you can do something like:
var frequencies = [];
var applicationName = [];
var mergedArray = Object.keys(scope.appApplications).map(function (key) {
frequencies.push(scope.appApplications[value]);
applications.push(key);
return {
applicationName: key,
frequency: scope.appApplications[value]
};
});
source to share
If you want to use underscore , you can do it as a one-chain function 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 the array and returns an array of results.
_.object()
turns ["applicationName","frequency"]
and ['a',1]
into {applicationName: 'a', frequency: 1}
.
source to share
You can have another variable (like targetJson) that will hold your target json. something like that.
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});
})
source to share