Javascript Object.entries ()

Il metodo JavaScript Object.entries () restituisce un array di coppie chiave-valore delle proprietà enumerabili dell'oggetto.

La sintassi del entries()metodo è:

 Object.entries(obj)

Il entries()metodo, essendo un metodo statico, viene chiamato utilizzando il Objectnome della classe.

entry () Parametri

Il entries()metodo comprende:

  • obj - L'oggetto di cui devono essere restituite le coppie chiave e valore della proprietà con chiave stringa enumerabile.

Valore restituito dalle voci ()

  • Restituisce un array delle coppie di proprietà (chiave, valore) con chiave stringa enumerabili dell'oggetto specificato .

Nota: l'ordinamento delle proprietà è lo stesso di quando si esegue il loop su di esse manualmente utilizzando for… inloop.

Esempio: utilizzo di Object.entries ()

 const obj = ( name: "Adam", age: 20, location: "Nepal" ); console.log(Object.entries(obj)); // ( ( 'name', 'Adam' ), ( 'age', 20 ), ( 'location', 'Nepal' ) ) // Array-like objects const obj1 = ( 0: "A", 1: "B", 2: "C" ); console.log(Object.entries(obj1)); // ( ( '0', 'A' ), ( '1', 'B' ), ( '2', 'C' ) ) // random key ordering const obj2 = ( 42: "a", 22: "b", 71: "c" ); // ( ( '22', 'b' ), ( '42', 'a' ), ( '71', 'c' ) ) -> arranged in numerical order of keys console.log(Object.entries(obj2)); // string -> from ES2015+, non objects are coerced to object const string = "code"; console.log(Object.entries(string)); // ( ( '0', 'c' ), ( '1', 'o' ), ( '2', 'd' ), ( '3', 'e' ) ) // primite types have no properties console.log(Object.entries(55)); // () // Iterating through key-value of objects for (const (key, value) of Object.entries(obj)) ( console.log(`$(key): $(value)`); )

Produzione

 (('name', 'Adam'), ('age', 20), ('location', 'Nepal')) (('0', 'A'), ('1', 'B'), ('2', 'C')) (('22', 'b'), ('42', 'a'), ('71', 'c')) (('0', 'c' ), ('1', 'o'), ('2', 'd'), ('3', 'e')) () nome: Adam età: 20 luogo: Nepal

Letture consigliate: Javascript Object.keys ()

Articoli interessanti...