📜  Javascript Object.entries()

📅  最后修改于: 2020-09-27 06:44:46             🧑  作者: Mango

JavaScript Object.entries()方法返回对象的可枚举属性的键值对数组。

entries()方法的语法为:

Object.entries(obj)

使用Object类名称调用作为静态方法的entries()方法。


entry()参数

entries()方法采用:

  • obj-将返回其可枚举的字符串键属性键和值对的对象。

从entry()返回值
  • 返回给定对象自己的可枚举字符串键属性[key,value]对的数组。

注意:属性的顺序与使用for...in循环手动遍历属性时的顺序相同。


示例:使用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}`);
}

输出

[ [ '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' ] ]
[]
name: Adam
age: 20
location: Nepal

推荐阅读: Javascript Object.keys()