關于Object.entries()方法的使用和實現方式
Object.entries()方法的使用和實現
1、定義
Object.entries()方法返回一個給定對象自身可枚舉屬性的鍵值對數組,其排列與使用 for...in 循環(huán)遍歷該對象時返回的順序一致(區(qū)別在于 for-in 循環(huán)還會枚舉原型鏈中的屬性)。
語法
Object.entries(obj)
參數
obj 可以返回其可枚舉屬性的鍵值對的對象。
返回值
給定對象自身可枚舉屬性的鍵值對數組。
描述
Object.entries()返回一個數組,其元素是與直接在object上找到的可枚舉屬性鍵值對相對應的數組。
屬性的順序與通過手動循環(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是數字類型,會按照從小到大枚舉
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循環(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方法返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值。
const obj = { foo: 'bar', baz: 42 };
Object.values(obj)
// ["bar", 42]返回數組的成員順序,與本章的《屬性的遍歷》部分介紹的排列規(guī)則一致。
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": 2Object.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;
}總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Javascript中函數名.length屬性用法分析(對比arguments.length)
這篇文章主要介紹了Javascript中函數名.length屬性用法,結合實例形式簡單對比分析了與arguments.length屬性的用法區(qū)別,需要的朋友可以參考下2016-09-09

