I have data returned from an API coming back in a response: response.data
[
{"amount":"45342",
"comment":"random text",
"currency":"USD"},
{"city":"LA",
"amount":"54366",
"lane_id":{"$oid":"5645999965a5b0"}}
]
I need to take only the amount and create a new set of objects like this:
[{amount: "45342"}, {amount: "54366"}]
The obvious way would be to push it through a loop like so:
var newArray = [];
var newObject;
var i, len;
for (len = response.data.length, i=0; i<len; ++i){
newObject = response.data[i];
newArray.push({amount: newObject.amount});
};
Is there a better way? I am running on angular 1.5 and jquery
1 Answer 1
you can use the map
function provided for all arrays. You would need to make sure that response.data
always returns an array, even in the case where nothing was returned from the api otherwise you can get an error.
var newArray = response.data.map(function(data) {
return {amount: data.amount}
});
would get you what you are looking for.
array.map
\$\endgroup\$