我需要一个键值对数组。如何将键值附加到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”插入键和值。请帮忙!
答案 0 :(得分:1)
您确实需要Array.prototype.push
。同样,在您要求键值对时,我假设您希望id
是键,而properties.name
是值。
let arrayOfCountries = [];
countryData.features.forEach(country => {
arrayOfCountries.push({
[country.id]: country.properties.name;
});
console.log(arrayOfCountries);
答案 1 :(得分:1)
{}
是一个对象,而不是数组。由[]
创建一个数组。您想使用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);