简体   繁体   中英

Appending key value pairs to an array in Javascript

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 !

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM