關(guān)于Object.entries()方法的使用和實現(xiàn)方式
Object.entries()方法的使用和實現(xiàn)
1、定義
Object.entries()
方法返回一個給定對象自身可枚舉屬性的鍵值對數(shù)組,其排列與使用 for...in
循環(huán)遍歷該對象時返回的順序一致(區(qū)別在于 for-in
循環(huán)還會枚舉原型鏈中的屬性)。
語法
Object.entries(obj)
參數(shù)
obj 可以返回其可枚舉屬性的鍵值對的對象。
返回值
給定對象自身可枚舉屬性的鍵值對數(shù)組。
描述
Object.entries()
返回一個數(shù)組
,其元素是與直接在object
上找到的可枚舉屬性鍵值對相對應(yīng)的數(shù)組。
屬性的順序與通過手動循環(huán)對象的屬性值所給出的順序相同。
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是數(shù)字類型,會按照從小到大枚舉 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'] ] // 非對象參數(shù)將被強(qiáng)制為對象 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 轉(zhuǎn)換為 Map // new Map() 構(gòu)造函數(shù)接受一個可迭代的entries。借助Object.entries方法你可以很容易的將Object轉(zhuǎn)換為Map: const obj = { foo: "bar", baz: 42 }; const map = new Map(Object.entries(obj)); console.log(map); // Map(2) { "foo" => "bar", "baz" => 42 } // 將 Map 轉(zhuǎn)換為 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、實現(xiàn)
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 '無法將參數(shù)轉(zhuǎn)換為對象!' } // 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')); // 無法將參數(shù)轉(zhuǎn)換為對象!
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 '參數(shù)不可編輯!'; } // 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)); // 參數(shù)不可編輯!
Object.keys(),Object.values(),Object.entries()
Object.keys()
ES5 引入了Object.keys方法,返回一個數(shù)組,成員是參數(shù)對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵名。
var obj = { foo: 'bar', baz: 42 }; Object.keys(obj) // ["foo", "baz"]
ES2017 引入了跟Object.keys配套的Object.values和Object.entries,作為遍歷一個對象的補(bǔ)充手段,供for...of循環(huán)使用。
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方法返回一個數(shù)組,成員是參數(shù)對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值。
const obj = { foo: 'bar', baz: 42 }; Object.values(obj) // ["bar", 42]
返回數(shù)組的成員順序,與本章的《屬性的遍歷》部分介紹的排列規(guī)則一致。
const obj = { 100: 'a', 2: 'b', 7: 'c' }; Object.values(obj) // ["b", "c", "a"]
上面代碼中,屬性名為數(shù)值的屬性,是按照數(shù)值大小,從小到大遍歷的,因此返回的順序是b、c、a。
Object.values只返回對象自身的可遍歷屬性。
const obj = Object.create({}, {p: {value: 42}}); Object.values(obj) // []
上面代碼中,Object.create方法的第二個參數(shù)添加的對象屬性(屬性p),如果不顯式聲明,默認(rèn)是不可遍歷的,因為p的屬性描述對象的enumerable默認(rèn)是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方法的參數(shù)是一個字符串,會返回各個字符組成的一個數(shù)組。
Object.values('foo') // ['f', 'o', 'o']
上面代碼中,字符串會先轉(zhuǎn)成一個類似數(shù)組的對象。字符串的每個字符,就是該對象的一個屬性。因此,Object.values返回每個屬性的鍵值,就是各個字符組成的一個數(shù)組。
如果參數(shù)不是對象,Object.values會先將其轉(zhuǎn)為對象。由于數(shù)值和布爾值的包裝對象,都不會為實例添加非繼承的屬性。所以,Object.values會返回空數(shù)組。
Object.values(42) // [] Object.values(true) // []
Object.entries()
Object.entries()方法返回一個數(shù)組,成員是參數(shù)對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值對數(shù)組。
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方法的另一個用處是,將對象轉(zhuǎn)為真正的Map結(jié)構(gòu)。
const obj = { foo: 'bar', baz: 42 }; const map = new Map(Object.entries(obj)); map // Map { foo: "bar", baz: 42 }
自己實現(xiàn)Object.entries方法,非常簡單。
// Generator函數(shù)的版本 function* entries(obj) { ? for (let key of Object.keys(obj)) { ? ? yield [key, obj[key]]; ? } } // 非Generator函數(shù)的版本 function entries(obj) { ? let arr = []; ? for (let key of Object.keys(obj)) { ? ? arr.push([key, obj[key]]); ? } ? return arr; }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JS實現(xiàn)手機(jī)號脫敏、郵箱脫敏、身份證號脫敏、姓名脫敏等常見脫敏代碼示例
這篇文章主要給大家介紹了關(guān)于JS實現(xiàn)手機(jī)號脫敏、郵箱脫敏、身份證號脫敏、姓名脫敏等常見脫敏的相關(guān)資料,脫敏的目的是保護(hù)用戶隱私,一種常見的方式是顯示部分字符,用星號或其他字符替代,需要的朋友可以參考下2024-02-02返回對象在當(dāng)前級別中是第幾個元素的實現(xiàn)代碼
我就是想怎么獲取 每個層 相對于父級層 是第幾個,需要的朋友可以參考下。2011-01-01