[英]Javascript insert an object to an array like this [{…}, {…}]
Suppose I have a variable called var testVar = [];
假设我有一个名为var testVar = [];
的变量And I have a data in ajax like this我在 ajax 中有这样的数据
{
"Country": "ALA Aland Islands",
"CountryCode": "AX",
"Slug": "ala-aland-islands",
"Population": 100000,
"Teenagers": 50000,
"Mid": 20000,
"Seniors": 30000
},
{
"Country": "Afghanistan",
"CountryCode": "AFR",
"Slug": "afghanistan",
"Population": 200000,
"Teenagers": 50000,
"Mid": 100000,
"Seniors": 50000
}
I'm trying to do a for loop and insert the population per country in the array (testVar) by doing it like this我正在尝试做一个 for 循环,并通过这样做将每个国家/地区的人口插入数组(testVar)中
function obj(key, val) {
this.key = key;
this.val = val;
}
for(i=0;i<data.lenght;i++){
var x = new obj("y",data[i].Population);
testVar.push(x);
}
although the above works, it still didn't achieve what I'm trying to do.尽管上述方法有效,但它仍然没有实现我想要做的事情。 what i want the data to look like should be something like this我希望数据看起来应该是这样的
[{...}], [{...}] instead of [obj,obj]
All we do is map
the ajax response
to only the population key.我们所做的只是map
ajax response
人口密钥。
let data = [{ "Country": "ALA Aland Islands", "CountryCode": "AX", "Slug": "ala-aland-islands", "Population": 100000, "Teenagers": 50000, "Mid": 20000, "Seniors": 30000 }, { "Country": "Afghanistan", "CountryCode": "AFR", "Slug": "afghanistan", "Population": 200000, "Teenagers": 50000, "Mid": 100000, "Seniors": 50000 } ]; console.log('Standard Approach'); console.log(data.map((location) => ({ Population: location.Population }))) console.log('Property Destructuring'); console.log(data.map(({Population}) => ({ Population }))) console.log('Using Y && Standard Approach'); console.log(data.map((location) => ({ y: location.Population }))) console.log('Using Y && Property Destructuring'); console.log(data.map(({Population}) => ({ y: Population })))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.