如何使用For循环生成字典数组

How to generate an array of dictionaries with a For loop

本文关键字:字典 数组 循环 何使用 For      更新时间:2023-09-26

我目前生成字典数组的方式非常硬,我宁愿不这样做。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>

你可以运行并检查它。。