Object.entries()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Object.entries()
静态方法返回一个数组,包含给定对象自有的可枚举字符串键属性的键值对。
尝试一下
const object1 = {
a: "somestring",
b: 42,
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// Expected output:
// "a: somestring"
// "b: 42"
语法
js
Object.entries(obj)
参数
obj
-
一个对象。
返回值
一个由给定对象自有的可枚举字符串键属性的键值对组成的数组。每个键值对都是一个包含两个元素的数组:第一个元素是属性的键(始终是字符串),第二个元素是属性值。
描述
Object.entries()
返回一个数组,其元素是直接在 object
上找到相应的可枚举字符串键属性的键值对数组。这与使用 for...in
循环迭代相同,只是使用 for...in
循环也枚举原型链中的属性。Object.entries()
返回的数组顺序和 for...in
循环提供的顺序相同。
如果只需要属性的键,请使用 Object.keys()
。如果只需要属性的值,请使用 Object.values()
。
示例
使用 Object.entries()
js
const obj = { foo: "bar", baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
// 类数组对象
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
// 具有随机键排序的类数组对象
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
// getFoo 是一个不可枚举的属性
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
},
},
);
myObj.foo = "bar";
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]
在基本类型中使用 Object.entries()
将 Object 转换成 Map
遍历对象
使用数组解构语法,你可以很容易地遍历对象。
js
// 使用 for...of 循环
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
// 使用数组方法
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-object.entries |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
entries |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.