JavaScript中的Object.entries()和Object.fromEntries()示例詳解
Object.entries()
1. 基本知識(shí)
用于將對(duì)象的可枚舉屬性轉(zhuǎn)換為一個(gè)數(shù)組
該數(shù)組包含對(duì)象自身的可枚舉屬性的鍵值對(duì)數(shù)組,每個(gè)鍵值對(duì)數(shù)組由兩個(gè)元素組成:
- 第一個(gè)元素是屬性名,
字符串(或符號(hào))
- 第二個(gè)元素是屬性值,
任何類型
對(duì)象的屬性默認(rèn)是可枚舉的,意味著它們可以在 for...in
循環(huán)中被枚舉出來
使用 Object.defineProperty
方法可以設(shè)置或修改屬性的可枚舉性
基本的用法如下:
- 基本用法:
const obj = { a: 1, b: 2, c: 3 }; const entries = Object.entries(obj); console.log(entries); // 輸出: [['a', 1], ['b', 2], ['c', 3]]
- 處理空對(duì)象:
const emptyObj = {}; const entries = Object.entries(emptyObj); console.log(entries); // 輸出: []
- 與其他方法的比較:
Object.keys(obj)
: 返回一個(gè)包含對(duì)象所有可枚舉屬性名的數(shù)組Object.values(obj)
:返回一個(gè)包含對(duì)象所有可枚舉屬性值的數(shù)組Object.entries(obj)
: 返回一個(gè)包含對(duì)象所有可枚舉屬性的鍵值對(duì)數(shù)組
const obj = { a: 1, b: 2, c: 3 }; console.log(Object.keys(obj)); // 輸出: ['a', 'b', 'c'] console.log(Object.values(obj)); // 輸出: [1, 2, 3] console.log(Object.entries(obj)); // 輸出: [['a', 1], ['b', 2], ['c', 3]]
- 非對(duì)象參數(shù):
如果傳入非對(duì)象參數(shù)(如 null 或 undefined),Object.entries
會(huì)拋出錯(cuò)誤
try { console.log(Object.entries(null)); } catch (e) { console.error(e); // 輸出: TypeError: Cannot convert undefined or null to object }
- 使用 for…of 迭代:
Object.entries
返回的數(shù)組可以使用for...of
迭代
const obj = { x: 10, y: 20, z: 30 }; for (const [key, value] of Object.entries(obj)) { console.log(`${key}: ${value}`); } // 輸出: // x: 10 // y: 20 // z: 30
2. Demo
示例 1:過濾對(duì)象的屬性
通過 Object.entries 結(jié)合 filter 方法,篩選出滿足特定條件的鍵值對(duì)
const obj = { a: 1, b: 2, c: 3, d: 4 }; const filteredEntries = Object.entries(obj).filter(([key, value]) => value > 2); console.log(filteredEntries); // 輸出: [['c', 3], ['d', 4]]
示例 2: 對(duì)象屬性值的轉(zhuǎn)換
使用 map 方法對(duì)對(duì)象屬性值進(jìn)行轉(zhuǎn)換,然后重新構(gòu)建對(duì)象
const obj = { name: 'Alice', age: 25 }; const transformedEntries = Object.entries(obj).map(([key, value]) => { return [key, typeof value === 'string' ? value.toUpperCase() : value]; }); const newObj = Object.fromEntries(transformedEntries); console.log(newObj); // 輸出: { name: 'ALICE', age: 25 }
示例 3:嵌套對(duì)象處理
const nestedObj = { user: { name: 'Bob', age: 30 }, location: { city: 'New York', country: 'USA' } }; const nestedEntries = Object.entries(nestedObj).flatMap(([key, value]) => Object.entries(value).map(([subKey, subValue]) => [`${key}.${subKey}`, subValue]) ); console.log(nestedEntries); // 輸出: [['user.name', 'Bob'], ['user.age', 30], ['location.city', 'New York'], ['location.country', 'USA']]
示例 4:動(dòng)態(tài)構(gòu)建對(duì)象
const entries = [['a', 1], ['b', 2], ['c', 3]]; const obj = Object.fromEntries(entries); console.log(obj); // 輸出: { a: 1, b: 2, c: 3 }
示例 5:結(jié)合其他方法進(jìn)行數(shù)據(jù)處理
使用 reduce 方法結(jié)合 Object.entries
對(duì)對(duì)象進(jìn)行復(fù)雜的數(shù)據(jù)處理
const obj = { apple: 10, banana: 20, cherry: 30 }; const total = Object.entries(obj).reduce((sum, [key, value]) => sum + value, 0); console.log(total); // 輸出: 60
示例 6:轉(zhuǎn)換對(duì)象為查詢字符串
const params = { name: 'Alice', age: 25, city: 'Wonderland' }; const queryString = Object.entries(params) .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`) .join('&'); console.log(queryString); // 輸出: 'name=Alice&age=25&city=Wonderland'
Object.fromEntries()
一、輕松將鍵值對(duì)數(shù)組轉(zhuǎn)為對(duì)象,后端數(shù)據(jù)處理神器
當(dāng)從后端接口拿到的數(shù)據(jù)是
[['key1', 'value1'], ['key2', 'value2']]
這種鍵值對(duì)數(shù)組格式時(shí),想把它轉(zhuǎn)為對(duì)象方便使用,傳統(tǒng)方法可能需要寫一堆循環(huán)代碼。Object.fromEntries()
方法完美解決這個(gè)痛點(diǎn),它是ES10
的新特性,在前后端數(shù)據(jù)交互
中堪稱“瑞士軍刀”。
// 假設(shè)后端返回的用戶信息是鍵值對(duì)數(shù)組 const userArray = [ ['name', 'Tom'], ['age', 28], ['email', 'tom@example.com'] ]; // 使用Object.fromEntries()將鍵值對(duì)數(shù)組轉(zhuǎn)為對(duì)象 const userObject = Object.fromEntries(userArray); console.log(userObject); // {name: 'Tom', age: 28, email: 'tom@example.com'}
在處理登錄接口返回?cái)?shù)據(jù)、表單提交數(shù)據(jù)解析等場(chǎng)景時(shí),這個(gè)方法能讓你少寫幾十行代碼,開發(fā)效率直接起飛!
總結(jié)
到此這篇關(guān)于JavaScript中的Object.entries()和Object.fromEntries()示例詳解的文章就介紹到這了,更多相關(guān)Js中Object.entries() 和Object.fromEntries()內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
寫出更好的JavaScript程序之undefined篇(中)
前一篇我介紹了幾種廣為使用的利用undefined這個(gè)概念值的辦法,這一篇我會(huì)介紹一些不太常見的辦法,其中還包括一個(gè)很巧妙的,我個(gè)人覺得很值得推廣的辦法。2009-11-11IE6/7 and IE8/9/10(IE7模式)依次隱藏具有absolute或relative的父元素和子元素后再顯示
多數(shù)情況下隱藏(設(shè)置display:none)一個(gè)元素,無需依次將其內(nèi)的所有子元素都隱藏。非要這么做,有時(shí)會(huì)碰到意想不到的bug。2011-07-07JavaScript動(dòng)態(tài)添加數(shù)據(jù)到表單并提交的幾種方式
這篇文章主要介紹了JavaScript動(dòng)態(tài)添加數(shù)據(jù)到表單并提交,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-06-06