I have a query from MySQL selecting all columns with two rows. It returns a result as expected, but what I want is to store all rows fetched to data, like this:
var response = {
data : result //result from mysql
};
But I don't want to display all the columns. Lets say the table has 4 columns. The result from the MySQL query is:
[
{
row1: 'a',
row2: 'b',
row3: 'c',
row4: 'd'
},
{
row1: 'e',
row2: 'f',
row3: 'g',
row4: 'h'
}
]
And I only want to pass row2 and row3 in response.data. I want it to have a result of:
data : [
{
row2: 'b',
row3: 'c'
},
{
row2: 'f',
row3: 'g'
}
]
How to do that? Note that I do not specify in the MySQL query that it will only return row2 and row3, since that MySQL call will be used in other calls.
I think you don't want to change the actual resopnse object because you've specified that the result will be used in other calls.
I tried following using simple javascript.
var response = {data:[
{
row1: 'a',
row2: 'b',
row3: 'c',
row4: 'd'
},
{
row1: 'e',
row2: 'f',
row3: 'g',
row4: 'h'
}
]};
var newResponse = {};
newResponse.data = response.data.map(function (rows) {
return {row2:rows.row2,row3:rows.row3};
});
console.log(newResponse); //your result object as you wanted
console.log(response); // the actual response object, just to verify it doesn't got changed
Use the underscore map function.
Like this:
var response = {};
response.data = _.map(result, function(row) {
var newRow = {};
newRow.row2 = row.row2;
newRow.row3 = row.row3;
return newRow;
});
Or you could simplify it with map and pick.
var response = {};
response.data = _.map(result, function(row) {
return _.pick(row, 'row2', 'row3');
});