Konwersja obiektu JS na tablicę za pomocą jQuery
Moja aplikacja tworzy obiekt JavaScript, jak poniżej:
myObj= {1:[Array-Data], 2:[Array-Data]}
Ale potrzebuję tego obiektu jako tablicy.
array[1]:[Array-Data]
array[2]:[Array-Data]
Więc próbowałem przekonwertować ten obiekt do tablicy przez iterację z {[3] } przez obiekt i dodanie elementu do tablicy:
x=[]
$.each(myObj, function(i,n) {
x.push(n);});
Czy istnieje lepszy sposób na konwersję obiektu na tablicę lub może funkcję?
17 answers
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
var array = $.map(myObj, function(value, index) {
return [value];
});
console.log(array);
Wyjście:
[[1, 2, 3], [4, 5, 6]]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-20 18:21:00
Jeśli szukasz podejścia funkcjonalnego:
var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });
Wyniki w:
[11, 22]
To samo z funkcją strzałki ES6:
Object.keys(obj).map(key => obj[key])
Z ES7 będziesz mógł używać Object.values
zamiast (więcej informacji):
var arr = Object.values(obj);
Lub jeśli używasz już podkreślenia / Lo-Dash:
var arr = _.values(obj)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-22 18:00:17
Myślę, że możesz użyć for in
, ale sprawdzanie, czy właściwość nie jest bezwładna
myObj= {1:[Array-Data], 2:[Array-Data]}
var arr =[];
for( var i in myObj ) {
if (myObj.hasOwnProperty(i)){
arr.push(myObj[i]);
}
}
EDIT - jeśli chcesz, możesz również zachować indeksy swojego obiektu, ale musisz sprawdzić, czy są liczbowe (i otrzymasz niezdefiniowane wartości dla brakujących indeksów:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
myObj= {1:[1,2], 2:[3,4]}
var arr =[];
for( var i in myObj ) {
if (myObj.hasOwnProperty(i)){
if (isNumber(i)){
arr[i] = myObj[i];
}else{
arr.push(myObj[i]);
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-28 11:13:21
Po prostu zrób
Object.values(obj);
To wszystko!Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-14 21:58:38
Jeśli znasz maksymalny indeks w swoim obiekcie, możesz wykonać następujące czynności:
var myObj = {
1: ['c', 'd'],
2: ['a', 'b']
},
myArr;
myObj.length = 3; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-15 06:51:14
Od obiektu ES5.keys () zwraca tablicę zawierającą właściwości zdefiniowane bezpośrednio na obiekcie (z wyłączeniem właściwości zdefiniowanych w łańcuchu prototypów):
Object.keys(yourObject).map(function(key){ return yourObject[key] });
ES6 idzie o krok dalej z funkcjami strzałek:
Object.keys(yourObject).map(key => yourObject[key]);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-12 17:13:32
x = [];
for( var i in myObj ) {
x[i] = myObj[i];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-28 10:34:12
Najlepszą metodą byłoby użycie tylko funkcji javascript:
var myArr = Array.prototype.slice.call(myObj, 0);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-26 15:05:41
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 lub ES6:
Object.keys(myObj).map(x => myObj[x])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-12 03:46:22
Obecnie jest na to prosty sposób: obiekt.wartości () .
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
console.log(Object.values(myObj));
Wyjście:
[[1, 2, 3], [4, 5, 6]]
To nie wymaga jQuery, zostało zdefiniowane w ECMAScript 2017.
Jest obsługiwany przez każdą nowoczesną przeglądarkę (zapomnij o IE).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-06 03:12:58
A może jQuery.makeArray(obj)
Tak zrobiłem to w mojej aplikacji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-31 21:24:13
Rozwiązanie jest bardzo proste
var my_obj = {1:[Array-Data], 2:[Array-Data]}
Object.keys(my_obj).map(function(property_name){
return my_obj[property_name];
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-17 16:08:24
Rozszerzenie do odpowiedzi bjornd .
var myObj = {
1: [1, [2], 3],
2: [4, 5, [6]]
}, count = 0,
i;
//count the JavaScript object length supporting IE < 9 also
for (i in myObj) {
if (myObj.hasOwnProperty(i)) {
count++;
}
}
//count = Object.keys(myObj).length;// but not support IE < 9
myObj.length = count + 1; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr);
Bibliografia
/ align = "left" / prototyp.slice()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:33:32
Jeśli chcesz zachować nazwę właściwości obiektu jako wartości. Przykład:
var fields = {
Name: { type: 'string', maxLength: 50 },
Age: { type: 'number', minValue: 0 }
}
Użycie Object.keys()
, Array.map()
i Object.assign()
:
var columns = Object.keys( fields ).map( p => Object.assign( fields[p], {field:p} ) )
wynik:
[ { field: 'Name', type: 'string', maxLength: 50 },
{ field: 'Age', type: 'number', minValue: 0 } ]
Explanation:
Object.keys()
wylicza wszystkie właściwości źródła; .map()
stosuje funkcję =>
do każdej właściwości i zwraca tablicę ; Object.assign()
łączy nazwę i wartość dla każdej właściwości.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-20 14:50:22
Zrobiłem niestandardową funkcję:
Object.prototype.toArray=function(){
var arr=new Array();
for( var i in this ) {
if (this.hasOwnProperty(i)){
arr.push(this[i]);
}
}
return arr;
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-16 02:48:34
Po kilku testach, oto ogólny obiekt do konwertera funkcji tablicy:
Masz obiekt:
var obj = {
some_key_1: "some_value_1"
some_key_2: "some_value_2"
};
Funkcja:
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;
}
Zastosowanie Funkcji:
var arr = ObjectToArray(obj);
Otrzymujesz:
arr { key: [ "some_key_1", "some_key_2" ], value: [ "some_value_1", "some_value_2" ], length: 2 }
Więc możesz osiągnąć wszystkie klucze i wartości, takie jak:
for (var i = 0; i < arr.length; i++)
{
console.log(arr.key[i] + " = " + arr.value[i]);
}
Wynik w konsoli:
some_key_1 = some_value_1 some_key_2 = some_value_2
Edit:
Lub w postaci prototypu:
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;
};
A następnie użyć jak:
console.log(obj.objectToArray);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-14 11:54:01
Możesz utworzyć prostą funkcję do konwersji z object
do array
, coś takiego może wykonać zadanie za Ciebie za pomocą czystego javascript:
var objectToArray = function(obj) {
var arr = [];
if ('object' !== typeof obj || 'undefined' === typeof obj || Array.isArray(obj)) {
return obj;
} else {
Object.keys(obj).map(x=>arr.push(obj[x]));
}
return arr;
};
Lub ten:
var objectToArray = function(obj) {
var arr =[];
for(let o in obj) {
if (obj.hasOwnProperty(o)) {
arr.push(obj[o]);
}
}
return arr;
};
I wywołaj i używaj funkcji jak poniżej:
var obj = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'};
objectToArray(obj); // return ["a", "b", "c", "d", "e"]
Również w przyszłości będziemy mieli coś o nazwie Object.values(obj)
, podobne do Object.keys(obj)
, które zwróci wszystkie właściwości dla Ciebie jako tablicę, ale nie jest jeszcze obsługiwane w wielu przeglądarkach...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-08 09:49:42