当接收不同的数组元素时,数组中的JSON对象相同
Same JSON ojbects in array when receiving differnt array elements
在我的NodeJS应用程序中,我在jade中获得了一个JSON对象(工作正常)。在中,我尝试只收集(srcTweets)相关数据,并将其返回到一个新的JSON对象(stgTweet)中。我将其用于动态表。
因此,我使用以下划线:
var srcTweets = [];
var srcTweets = !{JSON.stringify(tweets)};
var aantalSrcTweets = srcTweets.length;
//Loop throug all tweets and collect all relevant elementen from srcTweet:
var stgTweet = {}
var stgTweets = [];
console.info('----------START LOOP--------------------');
for(var i = 0; i < aantalSrcTweets; i++){
console.info(i);
stgTweet.Id = srcTweets[i]._id;
stgTweet.userId = srcTweets[i].user.id;
stgTweet.userFollowerCount = srcTweets[i].user.followers_count;
stgTweet.userFriendCount = srcTweets[i].user.friends_count;
stgTweet.userFavouritesCount = srcTweets[i].user.favourites_count;
stgTweet.text = srcTweets[i].text;
stgTweet.coordinates = srcTweets[i].coordinates;
stgTweet.userLocation = srcTweets[i].user.location;
stgTweets[i] = stgTweet;
console.info(stgTweets[i]);
console.info(i);
}
console.info('----------END LOOP--------------------');
//here i get the same items
console.info(stgTweets[0]);
console.info(stgTweets[1]);
当我打印数组"stgTweet[0]和stgTweed[1]"的不同索引号时,会显示相同的数据。我试图通过在for循环中记录元素来解决这个问题,但这看起来很好。我真的不知道该往哪里看。
如何用不同的对象代替同一个对象填充数组,上面的脚本中发生了什么。
以下是srcTweets:的示例
[
Object {
_id="56e19eb1ac5e621e0797c423",
truncated=false,
text="@Model_Symphony nu ja,
s... prima Energiequelle...",
more...
},
Object {
_id="56e1a73eac5e621e0797c424",
truncated=false,
text="Vandaag aangekondigd doo...",
more...
},
Object {
_id="56e1a7b4ac5e621e0797c425",
truncated=false,
text="Mooi bedrijfsbezoek aan ...",
more...
}
]
原因是对数组中的每个元素重用相同的对象,并且对象在Javascript中是通过引用分配的,所以stgTweets[0] === stgTweets[1]
。
相反,您可以将stgTweet
声明移动到循环中(或者直接重新分配值,如下所示),以便为每个数组元素创建一个新对象:
var stgTweets = new Array(aantalSrcTweets);
for (var i = 0; i < aantalSrcTweets; i++){
stgTweets[i] = {
Id: srcTweets[i]._id,
userId: srcTweets[i].user.id,
userFollowerCount: srcTweets[i].user.followers_count,
userFriendCount: srcTweets[i].user.friends_count,
userFavouritesCount: srcTweets[i].user.favourites_count,
text: srcTweets[i].text,
coordinates: srcTweets[i].coordinates,
userLocation: srcTweets[i].user.location
};
}
相关文章:
- 为DataTables aoColumnDefs创建JavaScript数组(JSON格式)
- 使用 Javascript 将行添加到数组 json
- PHP数组JSON编码和该对象在ExtJs中解码
- 数组json转换为数组json
- 将Blob文本转换为Javascript中的数组/JSON对象
- 如何合并这些数组/json 对象
- 尝试从数组 JSON 键中删除引号
- JavaScript 中的数组 JSON
- 在数组 JSON 格式的 JavaScript 变量末尾添加新地址
- 如何访问这个Javascript数组(JSON对象?)
- rails传递记录数组(JSON)
- 按值提取对象/数组json vs数组
- 获取具有子数组json值的数组的值
- Object对象数组Json.字符串数组的字符串化
- 如何在Ext js 4.1中过滤数组json
- PHP -多维数组Json
- 正在分析数组Json以选择Tag
- 试图将字符串数据转换为数值数据,将数据放入数组的数组(Json)
- 从数组json、javascript中的specf值中删除引号
- 使用JavaScript或jQuery读取数组JSON