0

Can someone help on how to push all object values into one array please?

  const countryObject = data.countryBorders

      for ( var i = 0; i < countryObject.length; i++ ) {

        let countries = []
        let country = countryObject[i].properties.name

        countries.push(country)

        console.log(contries)

it print

["Bahamas"]["Canada"]["Costa Rica"]["Cuba"]...

but I need it to print in one array under countries variable like

["Bahamas", "Canada", "Costa Rica", "Cuba"]

2 Answers 2

1

It would be much simpler using Array.map

const countries = data.countryBorders.map(country => country.properties.name);
console.log(countries);
Sign up to request clarification or add additional context in comments.

1 Comment

Hope you learnt something in the process @Coder_k
0

The issue is with where you are initializing the countries array. Since you have it in the for-loop, you are creating a new array for each iteration, resulting in the previous country to be lost.

You should initialize the countries variable before the for-loop, and then log it after the for-loop.

const countryObject = data.countryBorders;
const countries = [];

for ( var i = 0; i < countryObject.length; i++ ) {            
    let country = countryObject[i].properties.name;

    countries.push(country);
}

console.log(contries);

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.