Object.entries()方法如何实现及其具体使用场景有哪些?

2026-03-31 15:471阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1962个文字,预计阅读时间需要8分钟。

Object.entries()方法如何实现及其具体使用场景有哪些?

`Object.entries()` 方法的使用和实现:

`Object.entries()` 方法用于获取一个对象自身的可枚举属性的键值对数组。以下是一个简单的实现:

javascriptfunction objectEntries(obj) { let entries=[]; for (let key in obj) { if (obj.hasOwnProperty(key)) { entries.push([key, obj[key]]); } } return entries;}

此方法首先创建一个空数组 `entries`,然后使用 `for...in` 循环遍历对象的所有可枚举属性。通过 `hasOwnProperty` 方法检查属性是否是对象自身的属性,而不是继承自原型链的属性。如果是自身属性,则将其键值对添加到 `entries` 数组中。最后,返回这个数组。

此实现中 `for...in` 循环返回的顺序与属性在对象中定义的顺序一致,区别于 `Object.keys()` 方法返回的键的顺序,后者是按照字符串顺序排序的。

Object.entries()方法的使用和实现

1、定义

Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for...in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环还会枚举原型链中的属性)。

语法

Object.entries(obj)

参数

obj 可以返回其可枚举属性的键值对的对象。

返回值

给定对象自身可枚举属性的键值对数组。

描述

Object.entries()方法如何实现及其具体使用场景有哪些?

Object.entries()返回一个数组,其元素是与直接在object上找到的可枚举属性键值对相对应的数组

属性的顺序与通过手动循环对象的属性值所给出的顺序相同。

2、使用示例

const object = { a: 'string', b: 111, c: true, e: null, d: undefined, f: [3, 4, 5], g: { obj: '666' } }; for (const [key, value] of Object.entries(object)) { console.log(`${key}: ${value}`); } // expected output: // a: string // b: 111 // c: true // e: null // d: undefined // f: 3,4,5 // g: [object Object]

console.log(Object.entries(object));

// 正常对象枚举 const obj = { foo: 'bar', baz: 42 }; console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] // key为索引的对象 const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // key是数字类型,会按照从小到大枚举 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'] ] // 非对象参数将被强制为对象 console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // 通过 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" } // forEach 方法遍历 Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" }); // 将 Object 转换为 Map // new Map() 构造函数接受一个可迭代的entries。借助Object.entries方法你可以很容易的将Object转换为Map: const obj = { foo: "bar", baz: 42 }; const map = new Map(Object.entries(obj)); console.log(map); // Map(2) { "foo" => "bar", "baz" => 42 } // 将 Map 转换为 Object const objByMap = Object.fromEntries(map); console.log(objByMap); // { foo: 'bar', baz: 42 } // 获取 url 传参 const str = "page=1&&row=10&&id=2&&name=test" const params = new URLSearchParams(str) console.log(Object.fromEntries(params)) // { page: '1', row: '10', id: '2', name: 'test' }

3、实现

const entries = arg => { if (Array.isArray(arg)) return arg.map((x, index) => [`${index}`, x]); if (Object.prototype.toString.call(arg) === `[object Object]`) return Object.keys(arg).map(y => [y, arg[y]]); if (typeof arg === 'number') return []; throw '无法将参数转换为对象!' } // test Number console.log(entries(1)); // [] // test Object const obj = { foo: "bar", baz: 42 }; const map = new Map(entries(obj)); console.log(map); // Map(2) { "foo" => "bar", "baz" => 42 } // test Array const arr = [1, 2, 3]; console.log(entries(arr)); // [["0", 1], ["1", 2], ["2", 3]] // test Error console.log(entries('123')); // 无法将参数转换为对象!

const fromEntries = arg => { // Map if (Object.prototype.toString.call(arg) === '[object Map]') { const resMap = {}; for (const key of arg.keys()) resMap[key] = arg.get(key); return resMap; } // Array if (Array.isArray(arg)) { const resArr = {} arg.map(([key, value]) => resArr[key] = value); return resArr } throw '参数不可编辑!'; } // test Map const map = new Map(Object.entries({ foo: "bar", baz: 42 })); const obj = fromEntries(map); console.log(obj); // { foo: 'bar', baz: 42 } // test Array const arr = [['0', 'a'], ['1', 'b'], ['2', 'c']]; const obj = fromEntries(arr); console.log(obj); // { 0: 'a', 1: 'b', 2: 'c' } // test Error console.log(fromEntries(1)); // 参数不可编辑!

Object.keys(),Object.values(),Object.entries()

Object.keys()

ES5 引入了Object.keys方法,返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键名。

var obj = { foo: 'bar', baz: 42 }; Object.keys(obj) // ["foo", "baz"]

ES2017 引入了跟Object.keys配套的Object.values和Object.entries,作为遍历一个对象的补充手段,供for...of循环使用。

let {keys, values, entries} = Object; let obj = { a: 1, b: 2, c: 3 }; for (let key of keys(obj)) { console.log(key); // 'a', 'b', 'c' } for (let value of values(obj)) { console.log(value); // 1, 2, 3 } for (let [key, value] of entries(obj)) { console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3] }

Object.values()

Object.values方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值。

const obj = { foo: 'bar', baz: 42 }; Object.values(obj) // ["bar", 42]

返回数组的成员顺序,与本章的《属性的遍历》部分介绍的排列规则一致。

const obj = { 100: 'a', 2: 'b', 7: 'c' }; Object.values(obj) // ["b", "c", "a"]

上面代码中,属性名为数值的属性,是按照数值大小,从小到大遍历的,因此返回的顺序是b、c、a。

Object.values只返回对象自身的可遍历属性。

const obj = Object.create({}, {p: {value: 42}}); Object.values(obj) // []

上面代码中,Object.create方法的第二个参数添加的对象属性(属性p),如果不显式声明,默认是不可遍历的,因为p的属性描述对象的enumerable默认是false,Object.values不会返回这个属性。只要把enumerable改成true,Object.values就会返回属性p的值。

const obj = Object.create({}, {p: { value: 42, enumerable: true } }); Object.values(obj) // [42]

Object.values会过滤属性名为 Symbol 值的属性。

Object.values({ [Symbol()]: 123, foo: 'abc' }); // ['abc']

如果Object.values方法的参数是一个字符串,会返回各个字符组成的一个数组。

Object.values('foo') // ['f', 'o', 'o']

上面代码中,字符串会先转成一个类似数组的对象。字符串的每个字符,就是该对象的一个属性。因此,Object.values返回每个属性的键值,就是各个字符组成的一个数组。

如果参数不是对象,Object.values会先将其转为对象。由于数值和布尔值的包装对象,都不会为实例添加非继承的属性。所以,Object.values会返回空数组。

Object.values(42) // [] Object.values(true) // []

Object.entries()

Object.entries()方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。

const obj = { foo: 'bar', baz: 42 }; Object.entries(obj) // [ ["foo", "bar"], ["baz", 42] ]

除了返回值不一样,该方法的行为与Object.values基本一致。

如果原对象的属性名是一个 Symbol 值,该属性会被忽略。

Object.entries({ [Symbol()]: 123, foo: 'abc' }); // [ [ 'foo', 'abc' ] ]

上面代码中,原对象有两个属性,Object.entries只输出属性名非 Symbol 值的属性。将来可能会有Reflect.ownEntries()方法,返回对象自身的所有属性。

Object.entries的基本用途是遍历对象的属性。

let obj = { one: 1, two: 2 }; for (let [k, v] of Object.entries(obj)) {   console.log(     `${JSON.stringify(k)}: ${JSON.stringify(v)}`   ); } // "one": 1 // "two": 2

Object.entries方法的另一个用处是,将对象转为真正的Map结构。

const obj = { foo: 'bar', baz: 42 }; const map = new Map(Object.entries(obj)); map // Map { foo: "bar", baz: 42 }

自己实现Object.entries方法,非常简单。

// Generator函数的版本 function* entries(obj) {   for (let key of Object.keys(obj)) {     yield [key, obj[key]];   } } // 非Generator函数的版本 function entries(obj) {   let arr = [];   for (let key of Object.keys(obj)) {     arr.push([key, obj[key]]);   }   return arr; }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。

本文共计1962个文字,预计阅读时间需要8分钟。

Object.entries()方法如何实现及其具体使用场景有哪些?

`Object.entries()` 方法的使用和实现:

`Object.entries()` 方法用于获取一个对象自身的可枚举属性的键值对数组。以下是一个简单的实现:

javascriptfunction objectEntries(obj) { let entries=[]; for (let key in obj) { if (obj.hasOwnProperty(key)) { entries.push([key, obj[key]]); } } return entries;}

此方法首先创建一个空数组 `entries`,然后使用 `for...in` 循环遍历对象的所有可枚举属性。通过 `hasOwnProperty` 方法检查属性是否是对象自身的属性,而不是继承自原型链的属性。如果是自身属性,则将其键值对添加到 `entries` 数组中。最后,返回这个数组。

此实现中 `for...in` 循环返回的顺序与属性在对象中定义的顺序一致,区别于 `Object.keys()` 方法返回的键的顺序,后者是按照字符串顺序排序的。

Object.entries()方法的使用和实现

1、定义

Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for...in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环还会枚举原型链中的属性)。

语法

Object.entries(obj)

参数

obj 可以返回其可枚举属性的键值对的对象。

返回值

给定对象自身可枚举属性的键值对数组。

描述

Object.entries()方法如何实现及其具体使用场景有哪些?

Object.entries()返回一个数组,其元素是与直接在object上找到的可枚举属性键值对相对应的数组

属性的顺序与通过手动循环对象的属性值所给出的顺序相同。

2、使用示例

const object = { a: 'string', b: 111, c: true, e: null, d: undefined, f: [3, 4, 5], g: { obj: '666' } }; for (const [key, value] of Object.entries(object)) { console.log(`${key}: ${value}`); } // expected output: // a: string // b: 111 // c: true // e: null // d: undefined // f: 3,4,5 // g: [object Object]

console.log(Object.entries(object));

// 正常对象枚举 const obj = { foo: 'bar', baz: 42 }; console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] // key为索引的对象 const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // key是数字类型,会按照从小到大枚举 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'] ] // 非对象参数将被强制为对象 console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // 通过 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" } // forEach 方法遍历 Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" }); // 将 Object 转换为 Map // new Map() 构造函数接受一个可迭代的entries。借助Object.entries方法你可以很容易的将Object转换为Map: const obj = { foo: "bar", baz: 42 }; const map = new Map(Object.entries(obj)); console.log(map); // Map(2) { "foo" => "bar", "baz" => 42 } // 将 Map 转换为 Object const objByMap = Object.fromEntries(map); console.log(objByMap); // { foo: 'bar', baz: 42 } // 获取 url 传参 const str = "page=1&&row=10&&id=2&&name=test" const params = new URLSearchParams(str) console.log(Object.fromEntries(params)) // { page: '1', row: '10', id: '2', name: 'test' }

3、实现

const entries = arg => { if (Array.isArray(arg)) return arg.map((x, index) => [`${index}`, x]); if (Object.prototype.toString.call(arg) === `[object Object]`) return Object.keys(arg).map(y => [y, arg[y]]); if (typeof arg === 'number') return []; throw '无法将参数转换为对象!' } // test Number console.log(entries(1)); // [] // test Object const obj = { foo: "bar", baz: 42 }; const map = new Map(entries(obj)); console.log(map); // Map(2) { "foo" => "bar", "baz" => 42 } // test Array const arr = [1, 2, 3]; console.log(entries(arr)); // [["0", 1], ["1", 2], ["2", 3]] // test Error console.log(entries('123')); // 无法将参数转换为对象!

const fromEntries = arg => { // Map if (Object.prototype.toString.call(arg) === '[object Map]') { const resMap = {}; for (const key of arg.keys()) resMap[key] = arg.get(key); return resMap; } // Array if (Array.isArray(arg)) { const resArr = {} arg.map(([key, value]) => resArr[key] = value); return resArr } throw '参数不可编辑!'; } // test Map const map = new Map(Object.entries({ foo: "bar", baz: 42 })); const obj = fromEntries(map); console.log(obj); // { foo: 'bar', baz: 42 } // test Array const arr = [['0', 'a'], ['1', 'b'], ['2', 'c']]; const obj = fromEntries(arr); console.log(obj); // { 0: 'a', 1: 'b', 2: 'c' } // test Error console.log(fromEntries(1)); // 参数不可编辑!

Object.keys(),Object.values(),Object.entries()

Object.keys()

ES5 引入了Object.keys方法,返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键名。

var obj = { foo: 'bar', baz: 42 }; Object.keys(obj) // ["foo", "baz"]

ES2017 引入了跟Object.keys配套的Object.values和Object.entries,作为遍历一个对象的补充手段,供for...of循环使用。

let {keys, values, entries} = Object; let obj = { a: 1, b: 2, c: 3 }; for (let key of keys(obj)) { console.log(key); // 'a', 'b', 'c' } for (let value of values(obj)) { console.log(value); // 1, 2, 3 } for (let [key, value] of entries(obj)) { console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3] }

Object.values()

Object.values方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值。

const obj = { foo: 'bar', baz: 42 }; Object.values(obj) // ["bar", 42]

返回数组的成员顺序,与本章的《属性的遍历》部分介绍的排列规则一致。

const obj = { 100: 'a', 2: 'b', 7: 'c' }; Object.values(obj) // ["b", "c", "a"]

上面代码中,属性名为数值的属性,是按照数值大小,从小到大遍历的,因此返回的顺序是b、c、a。

Object.values只返回对象自身的可遍历属性。

const obj = Object.create({}, {p: {value: 42}}); Object.values(obj) // []

上面代码中,Object.create方法的第二个参数添加的对象属性(属性p),如果不显式声明,默认是不可遍历的,因为p的属性描述对象的enumerable默认是false,Object.values不会返回这个属性。只要把enumerable改成true,Object.values就会返回属性p的值。

const obj = Object.create({}, {p: { value: 42, enumerable: true } }); Object.values(obj) // [42]

Object.values会过滤属性名为 Symbol 值的属性。

Object.values({ [Symbol()]: 123, foo: 'abc' }); // ['abc']

如果Object.values方法的参数是一个字符串,会返回各个字符组成的一个数组。

Object.values('foo') // ['f', 'o', 'o']

上面代码中,字符串会先转成一个类似数组的对象。字符串的每个字符,就是该对象的一个属性。因此,Object.values返回每个属性的键值,就是各个字符组成的一个数组。

如果参数不是对象,Object.values会先将其转为对象。由于数值和布尔值的包装对象,都不会为实例添加非继承的属性。所以,Object.values会返回空数组。

Object.values(42) // [] Object.values(true) // []

Object.entries()

Object.entries()方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。

const obj = { foo: 'bar', baz: 42 }; Object.entries(obj) // [ ["foo", "bar"], ["baz", 42] ]

除了返回值不一样,该方法的行为与Object.values基本一致。

如果原对象的属性名是一个 Symbol 值,该属性会被忽略。

Object.entries({ [Symbol()]: 123, foo: 'abc' }); // [ [ 'foo', 'abc' ] ]

上面代码中,原对象有两个属性,Object.entries只输出属性名非 Symbol 值的属性。将来可能会有Reflect.ownEntries()方法,返回对象自身的所有属性。

Object.entries的基本用途是遍历对象的属性。

let obj = { one: 1, two: 2 }; for (let [k, v] of Object.entries(obj)) {   console.log(     `${JSON.stringify(k)}: ${JSON.stringify(v)}`   ); } // "one": 1 // "two": 2

Object.entries方法的另一个用处是,将对象转为真正的Map结构。

const obj = { foo: 'bar', baz: 42 }; const map = new Map(Object.entries(obj)); map // Map { foo: "bar", baz: 42 }

自己实现Object.entries方法,非常简单。

// Generator函数的版本 function* entries(obj) {   for (let key of Object.keys(obj)) {     yield [key, obj[key]];   } } // 非Generator函数的版本 function entries(obj) {   let arr = [];   for (let key of Object.keys(obj)) {     arr.push([key, obj[key]]);   }   return arr; }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。