简体   繁体   English

在jQuery中使用forloop(每个)将字典追加到数组

[英]append dictionaries to an array using forloop(each) in jquery

I have json data like below which i am getting from server 我有下面的JSON数据,我从服务器获取

result =     [
      {"transactions": 7, "products__name": "mark"}, 
      {"transactions": 12, "products__name": "vicky"}, 
      {"transactions": 30, "products__name": "daniel"},   
      {"transactions": 6, "products__name": "hurray "}]

Now i want to add extra items and change key names in the dictionaries in the above json response and i want the result in the below format 现在我想在上面的json响应中添加额外的项目并更改字典中的键名,并且我想要以下格式的结果

 result =    [
        { label: "mark",  data: 7, color: "#4572A7"},
        { label: "vicky",  data: 12, color: "#4572A7"},
        { label: "daniel",  data: 30, color: "#4572A7"},
        { label: "hurray",  data: 6, color: "#4572A7"},
    ];

I want to do the above logic with jquery and done the following 我想用jquery进行上述逻辑,并完成以下操作

      var array = [];
      var dictionary = {};
      $.each(result, function(key,val){
              dictionary['label'] = val.products__name;
              dictionary['data'] = val.revenue;
              dictionary['color'] = '#4572A7';
              console.log(dictionary);
            array.push(dictionary)
          });
         console.log(array);
});

So from the above jquery looping code, i can able to loop through the json array and can create a dictionary with different labels and items, but when i pushed it in to the new array , only the starting dictionary is being repeatedly inserting in to the array like the same record is displaying 4 times in the array 因此,从上面的jquery循环代码中,我可以循环遍历json数组,并可以创建具有不同标签和项目的字典,但是当我将其推入new array ,只有起始字典被重复插入到像相同记录的数组在数组中显示4次

So whats wrong in my code, can anyone please let me know what need to be done in order to push different dic items to new array ? 那么我的代码有什么问题,有人可以让我知道将不同的dic项目推到新数组时需要做什么吗?

use $.map() 使用$ .map()

var colors = [' #bee485', '#f67d79', '#fdd35b', '#a8eaf7'];
var dictionary = $.map(result, function (rec, idx) {
    return {
        label: rec.products__name,
        data: rec.transactions,
        color: colors[idx % colors.length]
    }
})

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM