Setelah beberapa tes, berikut ini adalah objek umum untuk fungsi array konverter:
Anda memiliki objek:
var obj = {
some_key_1: "some_value_1"
some_key_2: "some_value_2"
};
Fungsi:
function ObjectToArray(o)
{
var k = Object.getOwnPropertyNames(o);
var v = Object.values(o);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
}
Fungsi Gunakan:
var arr = ObjectToArray(obj);
Anda mendapatkan:
arr {
key: [
"some_key_1",
"some_key_2"
],
value: [
"some_value_1",
"some_value_2"
],
length: 2
}
Jadi, Anda dapat menjangkau semua kunci & nilai seperti:
for (var i = 0; i < arr.length; i++)
{
console.log(arr.key[i] + " = " + arr.value[i]);
}
Hasil di konsol:
some_key_1 = some_value_1
some_key_2 = some_value_2
Edit:
Atau dalam bentuk prototipe:
Object.prototype.objectToArray = function()
{
if (
typeof this != 'object' ||
typeof this.length != "undefined"
) {
return false;
}
var k = Object.getOwnPropertyNames(this);
var v = Object.values(this);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
};
Dan kemudian gunakan seperti:
console.log(obj.objectToArray);