如何在数组中推送值

时间:2015-03-05 17:30:03

标签: javascript arrays

我想知道如何将数据存储在这样的数组中,以便通过推送功能来实现。

这是代码

var data_array =  [];  

和数据看起来像那样

var my_data = {
              "2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
              "2012":{"name":"Agents","total":1997,"drilldown":"true"},
              "2013":{"name":"Coachs","total":1188,"drilldown":"true"},
              "2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
              "2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
                        };

任何改变这种插入和使用推送功能的方法的帮助。

4 个答案:

答案 0 :(得分:1)

可能会有所帮助,

您可以遍历对象的所有键并将每个键推入数组

var data_array =  [];  
var my_data = {
              "2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
              "2012":{"name":"Agents","total":1997,"drilldown":"true"},
              "2013":{"name":"Coachs","total":1188,"drilldown":"true"},
              "2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
              "2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};

var keysArray = Object.keys(my_data);

keysArray.forEach(function(key, index) {
  data_array.push({ key : my_data[key]});
});

console.log(data_array);

答案 1 :(得分:0)

试试这个(用大括号括起数据):

data_array.push( {"2011":{"name":"Team Leaders","total":93,"drilldown":"true"} })

答案 2 :(得分:0)

我不知道你想要什么。无论如何,我认为它适合你。

var personInfo = new Object();
var my_data = new Object();

personInfo.name = 'Team Leaders';
personInfo.total = 93;
personInfo.drilldown = 'true';

my_data.person1 = personInfo;
my_data.person2 = personInfo;

// confirm
var jsonType = JSON.stringify(my_data);
console.log(jsonType);

答案 3 :(得分:0)

我认为这就是你需要的

var data_array =  [];  
var my_data = {
              "2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
              "2012":{"name":"Agents","total":1997,"drilldown":"true"},
              "2013":{"name":"Coachs","total":1188,"drilldown":"true"},
              "2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
              "2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var data_keys= Object.keys(my_data);

data_keys.forEach(function(key, index) {
    var obj = {};
    obj[key] = my_data[key];
    data_array.push(obj);
});