John Geliberte John Geliberte - 27 days ago 12
Javascript Question

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.

i have an object that i wanted to be converted on array 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.
the site_key has the key.

i want to add my site_key to the site_value array as a Key.

example data:

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

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.

Answer

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;
});
Comments