简体   繁体   English

如何在现有数组javascript上添加键

[英]How to add Key on existing array javascript

im currently working on a project that uses javascript as it's front end and im having a bit trouble on adding a key on my existing array. 我目前正在开发一个使用javascript作为前端的项目,并且在在现有数组上添加键时遇到了一些麻烦。

i have an object that i wanted to be converted on array javascript. 我有一个想要在数组javascript上转换的对象。

here is my code on how to convert my object to array. 这是关于如何将对象转换为数组的代码。

        var obj = data[0];
        var site_value = Object.keys(obj).map(function (key) { return obj[key]; });

        var site_key = $.map( obj, function( value, key ) {
          return key;
        });

the site_value has the value of my objects. site_value具有我的对象的值。 the site_key has the key. site_key具有密钥。

i want to add my site_key to the site_value array as a Key. 我想将我的site_key作为键添加到site_value数组中。

example data: 示例数据:

site_value: 0:Array[4] 0:Array[4] 1:Array[1] 2:Array[1] 3:Array[0] site_value:0:Array [4] 0:Array [4] 1:Array [1] 2:Array [1] 3:Array [0]

site_key: site_key:

Array[49]
  0:"AGB"
  1:"BAK"
  2:"BAN"
  3:"BAR"

i want my array to be 我希望我的数组成为

AGB:Array[4]
  0:Array[4]
  1:Array[1]
  2:Array[1]
  3:Array[0]

Update: 更新:

Here is my object. 这是我的对象。

Array[1]0: 
  Object
    AGB: Array[4]
    BAK: Array[4]
    BAN: Array[4]

etc. 等等

I might be misunderstanding the question, sorry if I am. 我可能会误解这个问题,对不起。 I think you would like to use a key "AGB" instead of an integer for an array index. 我想您想为数组索引使用键“ AGB”而不是整数。 In this case, you would probably be better served to use an object instead of an array. 在这种情况下,最好使用对象而不是数组。 Maybe something like this 也许像这样

var myObject = {
 AGB: Array[4],
 AGBarrays: [Array[4],Array[1],Array[1],Array[0]]
};

Then you could access AGB by key and your additional arrays by index 然后,您可以通过键访问AGB,并通过索引访问其他数组

You have almost done it and I have modified it a bit below to return it as array object, 您已经差不多完成了,我在下面做了一些修改,以将其作为数组对象返回,

var obj = data[0];

var site_value = Object.keys(obj).map(function (key) { 
    var output = {};
    output[key] = obj[key];

    return output;
});

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

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