在Javascript中将键值对追加到数组

在Javascript中将键值对追加到数组,javascript,arrays,Javascript,Arrays,我需要一个键值对数组。如何在for循环内的数组中追加键值 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("

我需要一个键值对数组。如何在for循环内的数组中追加键值

  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) 

此代码仅提供最后一个国家/地区id和名称。我想知道在这种情况下如何附加值。我得到的答案是“push”,但我不知道如何使用“push”插入键和值。请帮忙

您确实需要
Array.prototype.push
。另外,当您请求一个键值对时,我假设您希望
id
作为键,而
properties.name
作为值

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

为此,您确实需要
Array.prototype.push
。另外,当您请求一个键值对时,我假设您希望
id
作为键,而
properties.name
作为值

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

{}
是一个对象,而不是数组。数组由
[]
创建。您要做的是使用
map

constcountrydata={features:[{id:1,properties:{name:'Foo'}},{id:2,properties:{name:'Bar'}]};
const countries=countryData.features.map({id,properties})=>({id,name:properties.name}));

控制台日志(国家)
{}
是一个对象,而不是数组。数组由
[]
创建。您要做的是使用
map

constcountrydata={features:[{id:1,properties:{name:'Foo'}},{id:2,properties:{name:'Bar'}]};
const countries=countryData.features.map({id,properties})=>({id,name:properties.name}));

控制台日志(国家)在处理JavaScript时,您应该使用驼峰大小写并删除所有下划线。@ahbon snake_case vs camelCase完全优先。在处理JavaScript时,您应该使用驼峰大小写并删除所有下划线。@ahbon snake_case vs camelCase完全优先。