Reputation: 462
I have a JS array, for example:
const array1 = [{"entrance":"20","a":"10"},{"entrance":"15","b":"25"}];
I want to get entrance
values as a new array. Till today I'm using a for-loop
to do it, like this:
var entrance = [];
for(i=0;i<array1.length;i++){
entrance[i] = array1[i]["entrance"];
}
This works perfect, but I wonder if there is a prettier way to do this. Do you have any suggestions?
Upvotes: 1
Views: 42
Reputation: 1950
It has not been mentioned yet. You could use forEach
:
const array1 = [{"entrance":"20","a":"10"},{"entrance":"15","b":"25"}];
const res = [];
array1.forEach((obj) => {res.push(obj.entrance)});
console.log(res);
Upvotes: 0
Reputation: 10652
Pretty way using map and destructuring:
const array1 = [{"entrance":"20","a":"10"},{"entrance":"15","b":"25"}];
const entrances = array1.map(({ entrance }) => entrance);
Upvotes: 0
Reputation: 68933
You can try with map()
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array1 = [{"entrance":"20","a":"10"},{"entrance":"15","b":"25"}];
var entrance = array1.map(i => i.entrance);
console.log(entrance);
Upvotes: 1
Reputation: 8515
Use .map()
:
const array1 = [{"entrance":"20","a":"10"},{"entrance":"15","b":"25"}];
const entrance = array1.map((e) => e.entrance);
console.log(entrance);
Upvotes: 4