0

I need an array of key value pairs. How do I append key value in an array inside a for loop.

  array_of_countries = {};
  country_data.features.forEach(each_country => { 
    array_of_countries.id = each_country.id;
    array_of_countries.country_name = each_country.properties.name;
        });
  console.log("array of countries", array_of_countries) 

This code only gives the last country id and name. I would like to know how to append values in this case. I get the answer as "push" but I am not sure how to use "push" for inserting a key and value. Please help !

2
  • You should use camel case and remove all your underscores when you’re dealing with JavaScript.. Commented Jun 10, 2019 at 22:23
  • @ahbon snake_case vs camelCase is purely preferential. Commented Jun 11, 2019 at 0:18

2 Answers 2

1

{} is an object, not an array. An array is created by []. What you want to do is done using map

const countryData = {features: [{id: 1, properties: {name: 'Foo'}}, {id: 2, properties: {name: 'Bar'}}]};

const countries = countryData.features.map(({id, properties}) => ({id, name: properties.name}));
console.log(countries);

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

Comments

1

You do need Array.prototype.push for this. Also as you asked for a key-value pair, I assume you want the id to be the key and the properties.name to be the value.

let arrayOfCountries = [];
countryData.features.forEach(country => {
  arrayOfCountries.push({ 
    [country.id]: country.properties.name;
});
console.log(arrayOfCountries);

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.