Reputation: 2452
In our project we are getting below data from DB in following format.
[
[
"ClearDB",
"[email protected]",
"com.test.cleardb"
],
[
"Cricbuzz",
"[email protected]",
"com.test.cricbuzz"
],
[
"Hangout",
"[email protected]",
"com.test.hangout"
]
]
I want this in key value format as mentioned below
[
{
"projname": "ClearDB",
"projmanager": "[email protected]",
"package": "com.test.cleardb"
},
{
"projname": "Cricbuzz",
"projmanager": "[email protected]",
"package": "com.test.cricbuzz"
},
{
"projname": "Hangout",
"projmanager": "[email protected]",
"package": "com.test.hangout"
}
]
Please provide me a proper way to implement this.
Upvotes: 1
Views: 115
Reputation: 1115
if
var array =[
[
"ClearDB",
"[email protected]",
"com.test.cleardb"
],
[
"Cricbuzz",
"[email protected]",
"com.test.cricbuzz"
],
[
"Hangout",
"[email protected]",
"com.test.hangout"
]
];
then
var obj = [];
array.each(function(item){ obj.push({"projname": item[0],
"projmanager":item[1],
"package": item[2]})
});
Edit:
Using Jquery
var obj = [];
$.each(array,function(key,value){ obj.push({"projname": value[0],
"projmanager":value[1],
"package": value[2]})
});
Using javascript
var obj = [];
array.forEach(function(item){ obj.push({"projname": item[0],
"projmanager":item[1],
"package": item[2]})
});
Upvotes: 1
Reputation:
In ES6:
input . map(([projname, projmanager, package]) => ({projname, projmanager, package}));
The part in []
deconstructs the parameter to map
, which is one of the subarrays, assigning the first element to projname
, and so on. The part in {}
creates and returns an object with a key of 'projname'
whose value is projname
, etc.
If you want to generalize this to use any array of field names (['projname', 'projmanager', 'package']
):
input . map(
values =>
values . reduce(
(result, value, i) => {
result[fieldnames[i]] = value;
return result;
},
{}
)
);
Upvotes: 1
Reputation: 21
Suppose the data you are getting from database is stored in variable 'abc'
var abc = [];
var output = [];
for(var i = 0; i< abc.length; i++){
output[i] = {};
output[i].projname = abc[i][0];
output[i].projmanager = abc[i][1];
output[i].package = abc[i][2];
}
Note: 'abc' is the variable where you are storing data from DB.
Upvotes: 1
Reputation: 14982
with Array.prototype.map
:
var results = db.map(function (v) {
return {
projname: v[0],
projmanager: v[1],
package: v[2]
};
});
Upvotes: 4
Reputation: 239443
You can simply create a new object for each of the arrays, and create an array of objects with map
function, like this
var keys = ["projname", "projmanager", "package"];
console.log(data.map(function (arr) {
var obj = {};
keys.forEach(function (key, idx) { obj[key] = arr[idx]; });
return obj;
}));
Output
[ { projname: 'ClearDB',
projmanager: '[email protected]',
package: 'com.test.cleardb' },
{ projname: 'Cricbuzz',
projmanager: '[email protected]',
package: 'com.test.cricbuzz' },
{ projname: 'Hangout',
projmanager: '[email protected]',
package: 'com.test.hangout' } ]
Upvotes: 6