[英]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. 如何在一个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)
This code only gives the last country id and name. 该代码仅提供最后的国家/地区ID和名称。 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. 我得到的答案是“ push”,但是我不确定如何使用“ push”插入键和值。 Please help ! 请帮忙 !
You do need Array.prototype.push
for this. 为此,您确实需要Array.prototype.push
。 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. 同样,当您要求提供键值对时,我假设您希望id
是键,而properties.name
是值。
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
您想要做的是使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.