如何使用for循环创建对象数组
How to create an array of objects with a for loop
我有一个名为listData的对象数组,我想从其中调用某些信息到一个单独的名为marker的数组中。
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
});
}
对于这样的数据返回,我喜欢使用"map"。别人贴的没什么问题,我只是更喜欢这种简洁的语法。我假设你不正确地引用了初始值。你没有在循环中使用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
}
})
从您的代码中,我假设您需要以下内容:
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
}
);
您只需要循环listData
并为该数组(或数组类对象)的每个项添加一个新对象到markers
数组。所以我不明白你为什么用this.state
来访问listData
试试这个,我想这就是你想要的。
删除this
并从state
开始层次结构,如果没有帮助,您可以删除this.state
并开始后记。
var markers = [];
for(var i = 0; i < 5; i++){
markers.push(
{
latitude:'0123',
longitude:'0345'
});
}
console.log(markers);
更改和添加 values
相关文章:
- 如何在jquery中从$.each循环创建对象数组
- 无法创建对象数组
- 创建对象数组的封装问题
- 下划线 从对象元素创建对象数组
- 读取 json 以使用 jQuery .each() 创建对象数组
- 基于文件名数据创建对象数组
- 按键/值在数组内创建对象数组
- 如何从字符串创建对象数组
- 如何从javascript中具有相同键的对象创建对象数组,对象中包含数组
- 如何从多个数组创建对象数组
- 如何在json中创建对象数组
- 在javascript中创建对象数组
- 根据id对对象进行分组,并创建对象数组
- 如何使用javascript循环创建对象数组
- 我如何在函数参数中创建对象数组,为每个对象调用函数
- 从数组中创建对象数组
- jQuery .each()创建对象数组
- 如何使用html dom为国家列表创建对象数组
- JavaScript / mongoose - 循环访问数组以创建对象数组
- 如果我们使用new array (len).fil({})创建对象数组;然后在任意一个对象中添加一个键,它会被反射到所有