如何使用For循环生成字典数组
How to generate an array of dictionaries with a For loop
我目前生成字典数组的方式非常硬,我宁愿不这样做。Top 3
不一定有3个项目,我使用这个名称还有其他原因。例如,如果我知道Top 3
除了搜索项之外还包含两个项目,它将看起来像这样:
var top3Titles = [];
var top3Prices = [];
var top3ImgURLS = [];
var top3ItemURLS = [];
//where the title, price, and img url are sent over to the app
matchCenterItems.forEach(function(item) {
var title = item.title[0];
var price = item.sellingStatus[0].convertedCurrentPrice[0].__value__;
var imgURL = item.galleryURL[0];
var itemURL = item.viewItemURL[0];
top3Titles.push(title);
top3Prices.push(price);
top3ImgURLS.push(imgURL);
top3ItemURLS.push(itemURL);
});
// 10 results per MC Item, only showing 4 by default
var top3 =
{
"Top 3":
[
{
"Search Term": searchTerm
},
{
"Title": top3Titles[0],
"Price": top3Prices[0],
"Image URL": top3ImgURLS[0],
"Item URL": top3ItemURLS[0]
},
{
"Title": top3Titles[1],
"Price": top3Prices[1],
"Image URL": top3ImgURLS[1],
"Item URL": top3ItemURLS[1]
},
]
};
return top3;
相反,我想做的是让初始Search Term
之后的字典数量取决于matchCenterItems
数组中有多少item
对象。我想我可以使用for循环来实现这一点,但我不完全确定如何为此目的格式化它。例如,我希望它是一个具有title属性的对象,而不是拥有单独的title、price等数组。
您可以在top3
中初始化一个数组,并在迭代一个或多个数组(top3Titles、top3Prices等)时添加对象。
像这样:
var top3 = {'Top 3': [{'Search Term': searchTerm}]};
for (var i in top3Titles) {
top3['Top 3'].push({
'Title': top3Titles[i],
'Price': top3Prices[i],
'Image URL': top3ImgURLS[i],
'Item URL': top3ItemURLS[i]
});
}
或者,更好的是,你可以用替换你发布的所有内容
var top3 = {'Top 3': [{'Search Term': searchTerm}]};
matchCenterItems.forEach(function(item) {
top3['Top 3'].push(
{
'Title': item.title[0],
'Price': item.sellingStatus[0].convertedCurrentPrice[0].__value__,
'Image URL': item.galleryURL[0],
'Item URL': item.viewItemURL[0]
});
});
return top3;
但这里的重点是,return
属于函数内部,正如我在对您的问题的评论中告诉您的那样。
我在JavaScript方面没有很好的实践,但我可以给你演示如何使用for循环生成dict数组
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var arr=[];
var i;
var text="";
for(i=0;i<10;i++){
<!-- Creating 10 dictionary in array and initialise with some->
<!--value to check->
arr.push({firstName : "John"})
}
<!-- check that dict is working or not->
for(i=0;i<10;i++){
text=text+arr[i].firstName+'<br />'
}
document.getElementById("demo").innerHTML =
text;
</script>
</body>
</html>
你可以运行并检查它。。
相关文章:
- javascript结合了数组和字典
- 检查字符串是否在字典内的数组中
- 从iOS向javascript函数传递字典数组
- 解析Python字典中的javaScript数组
- 用Javascript从一个大的2D数组中编程创建一个字典
- 在JavaScript中,从一组数组递归地构建一个字典/嵌套对象
- 包含键和值数组的字典
- 如何将字典数组转换为数组数组
- 将字典数组传递给 Javascript
- 将数组中的元素替换为相应的字典项 JavaScript
- 在 javascript 中使用字典(关联数组)中的变量
- 使用 Json.Net 将 JavaScript 关联数组反序列化为 C# 字典
- JQuery 遍历字典数组
- 使用角度 js 迭代字典数组
- 在JS中将对象用作字典,将数组用作键
- 链表与字典数组
- 如何使用For循环生成字典数组
- 在javascript的字典数组中搜索id
- 如何将一个字典数组整理成一个数组字典
- 如何使用javascript(函数式编程)对特定键属性上的字典数组进行分组和转换