[英]How to create an array of objects with a for loop
I have a array of objects called listData that I would like to call certain information from into a separate called markers. 我有一个名为listData的对象数组,我想将某些信息从一个单独的称为标记的对象中调用。
var markers = [];
for(let i=0;i<listData.length;i++){
markers.push({
latitude:this.state.listData[i].geometry.location.lat,
longitude:this.state.listData[i].geometry.location.lng,
title:this.state.listData[i].name
});
}
but it is not working. 但它不起作用。
I like to use "map" for such data returns. 我喜欢将“地图”用于此类数据返回。 Nothing wrong with what others posted, I just like this concise syntax a bit better. 其他人发布的内容没有错,我更喜欢这种简洁的语法。 I am assuming you are referencing the initially value incorrectly. 我假设您错误地引用了初始值。 You didn't use this.state.listData in your loop. 您没有在循环中使用this.state.listData。
var markers = this.state.listData.map(function(v){
return {
latitude:v.geometry.location.lat,
longitude:v.geometry.location.lng,
title:v.name
}
})
From your code, I assume that you need something like the following: 从您的代码中,我假设您需要以下内容:
for( let i=0; i < listData.length; i++ ){
markers.push(
{
latitude: listData[i].geometry.location.lat,
longitude: listData[i].geometry.location.lng,
title: listData[i].name
}
);
You just want to loop through listData
and add for each item of this array (or array like object) a new object to the markers
array. 您只想遍历listData
并为此数组(或类似对象的数组)的每一项添加一个新对象到markers
数组。 So I don't get why you used this.state
to access the listData
. 所以我不明白为什么您使用this.state
访问listData
。
Try this, i think this is what you want. 试试这个,我想这就是你想要的。
Remove this
and start the hierarchy from state
, if its not helping you can remove both this.state
and start afterwords. 删除this
并从state
启动层次结构,如果它没有帮助,则可以删除this.state
和start this.state
。
var markers = []; for(var i = 0; i < 5; i++){ markers.push( { latitude:'0123', longitude:'0345' }); } console.log(markers);
Change and Add values
as you desire for yourself. 随心所欲改变和增加 values
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.