我需要一个键值对数组。如何在 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”来插入键和值。请帮忙!
最佳答案
{}
是一个对象,而不是数组。数组由[]
创建。您想要做的事情是使用 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);
关于javascript - 在 Javascript 中将键值对附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56534210/