Javascript 使用多维数组创建多维对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11648586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:39:28  来源:igfitidea点击:

Create multidimensional object with multidimensional arrays

javascriptflotjquery

提问by Kasper Skov

Im trying to build a somewhat advanced "Flot" jQuery pluging graph. For that, I need a multidimensional object (or at least I think it is).

我正在尝试构建一个有点高级的“Flot”jQuery 插件图。为此,我需要一个多维对象(或者至少我认为是)。

The structure should look like this:

结构应如下所示:

var datasets = {
        "usa": {
            label: "USA",
            data: [[1988, 483994], [1989, 479060], [1990, 457648], [1991, 401949], [1992, 424705], [1993, 402375], [1994, 377867], [1995, 357382], [1996, 337946], [1997, 336185], [1998, 328611], [1999, 329421], [2000, 342172], [2001, 344932], [2002, 387303], [2003, 440813], [2004, 480451], [2005, 504638], [2006, 528692]]
        },        
        "russia": {
            label: "Russia",
            data: [[1988, 218000], [1989, 203000], [1990, 171000], [1992, 42500], [1993, 37600], [1994, 36600], [1995, 21700], [1996, 19200], [1997, 21300], [1998, 13600], [1999, 14000], [2000, 19100], [2001, 21300], [2002, 23600], [2003, 25100], [2004, 26100], [2005, 31100], [2006, 34700]]
        }
};

From my code-behind i've generated some lists looking like this (Not the same data, but dont mind that):

从我的代码隐藏中,我生成了一些看起来像这样的列表(不是相同的数据,但不要介意):

<ul id="MOBILISATION">
  <li data-key="2012/3/27">02:10</li>
  <li data-key="2012/3/28">05:25</li>
  <li data-key="2012/3/29">09:21</li>
  <li data-key="2012/3/30">00:00</li>
  <li data-key="2012/3/31">00:00</li>
</ul>
<ul id="OPERATIONS">
  <li data-key="2012/3/27">19:51</li>
  <li data-key="2012/3/28">18:35</li>
  <li data-key="2012/3/29">14:39</li>
  <li data-key="2012/3/30">07:46</li>
  <li data-key="2012/3/31">10:26</li>
</ul>

Where "USA/usa" is "MOBILISATION", "1988" is "2012/3/27" and "483994" is "02:10". You get picture!!??

其中“USA/usa”是“MOBILISATION”,“1988”是“2012/3/27”,“483994”是“02:10”。有图吗!!!?

I've tried writing some jQuery, but it obviously doesnt work:

我试过写一些 jQuery,但它显然不起作用:

    var objects = [];
    var array = [];
    var categoryName = "";
    $('div#Container ul').each(function () {
        catName = $(this).attr('id');
        $('li', this).each(function () {
            array.push([new Date($(this).data('key')).getTime(), $(this).text()]);
        });

        objects.push({ categoryName: { label: categoryName, data: array} });
    });
    var datasets = objects;

As you can see i've used push to objectsarray. Clearly thats not giving me the result I want. Im kindda loosing whats up and down in this, as its the first time im working with javascript/jQuery objects. Whats the best solution for this?

如您所见,我使用了推送到objects数组。显然那没有给我我想要的结果。我有点失去了这方面的东西,因为这是我第一次使用 javascript/jQuery 对象。什么是最好的解决方案?

采纳答案by Bergi

Your datasets is an object, not an array - you can't push to it. Also, your variable categoryNamedoes not work like that (read more on dot and bracket notation). Try this:

你的数据集是一个对象,而不是一个数组——你不能推送到它。此外,您的变量categoryName不会像那样工作(阅读更多关于点和括号表示法)。尝试这个:

var datasets = {};
$('div#Container ul').each(function () {
    catName = this.id;
    var array = [];
    $('li', this).each(function () {
        array.push([
          new Date($(this).data('key')).getTime(),
          $(this).text()
        ]);
    });
    datasets[catName.toLowercase()] = {
        label: catName.toUppercase(),
        data: array
    };
});

Also, I'm not sure whether you really would need to create Dateobjects, but that depends on your in- and output format.

另外,我不确定您是否真的需要创建Date对象,但这取决于您的输入和输出格式。

回答by Joe Green

Change var objects = [];to var objects = {};and change

更改var objects = [];var objects = {};与变化

objects.push({ categoryName: { label: categoryName, data: array} });

to

objects[categoryName] = { label: categoryName, data: array};

The problem you have with JSON objects is in setting properties with a variable index. Yuo can use array notation to do that, as above.

JSON 对象的问题在于使用变量索引设置属性。Yuo 可以使用数组表示法来做到这一点,如上所述。

回答by Utkanos

Try

尝试

    var data = {};
    $('div#Container ul').each(function() {
        var sub_obj = data[$(this).attr('id').toLowerCase()] = {
            label: $(this).attr('id').toUpperCase(),
            data: []
        };
        $(this).children('li').each(function() {
            sub_obj.data.push([$(this).data('key'), $(this).text()]);
        });
    });
    console.log(data);

回答by user10170700

function convertObject(obj, key) {
    let returnObje = {};
    if (!key) key = "";
    else key = key + "_";
    Object.keys(obj).forEach(function (k1) {
        if (obj[k1] != null && typeof obj[k1] == "object") {
            returnObje = Object.assign({}, returnObje, convertObject(obj[k1], key + k1))
        } else
            returnObje[key + k1] = obj[k1];
    });
    return returnObje;
}

var hotels = { 
                     "hilton": {"name": "hilton hotel" },
                     "newton": {"name": "newton hotel"}
                 };

convertObject(hotels);