1

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?

4 Answers 4

4

Use .map():

const array1 = [{"entrance":"20","a":"10"},{"entrance":"15","b":"25"}];
const entrance = array1.map((e) => e.entrance);

console.log(entrance);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

Pretty way using map and destructuring:

const array1 = [{"entrance":"20","a":"10"},{"entrance":"15","b":"25"}];
const entrances = array1.map(({ entrance }) => entrance);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.