阿里云主机折上折
  • 微信号
Current Site:Index > Object.fromEntries()

Object.fromEntries()

Author:Chuan Chen 阅读数:63749人阅读 分类: JavaScript

Object.fromEntries() is a static method introduced in ECMAScript 10 (ES2019) that converts a list of key-value pairs into an object. It addresses the inverse operation of Object.entries(), making the conversion between objects and iterable structures more flexible.

Basic Syntax and Functionality

Object.fromEntries() takes an iterable (typically an array) as an argument, where each element is a two-element array (i.e., a key-value pair). The method converts these pairs into a new object:

const entries = [['a', 1], ['b', 2], ['c', 3]];
const obj = Object.fromEntries(entries);
console.log(obj); // { a: 1, b: 2, c: 3 }

If the iterable contains duplicate keys, the latter key-value pair will overwrite the former:

const entries = [['a', 1], ['a', 2]];
const obj = Object.fromEntries(entries);
console.log(obj); // { a: 2 }

Relationship with Object.entries()

Object.fromEntries() is the inverse of Object.entries(). Combining the two enables shallow copying or transforming objects:

const original = { x: 10, y: 20 };
const copied = Object.fromEntries(Object.entries(original));
console.log(copied); // { x: 10, y: 20 }

This pattern is particularly useful for filtering or modifying object properties:

const user = { name: 'Alice', age: 25, password: 'secret' };
const safeUser = Object.fromEntries(
  Object.entries(user).filter(([key]) => key !== 'password')
);
console.log(safeUser); // { name: 'Alice', age: 25 }

Handling Map Structures

Object.fromEntries() can directly convert a Map into a plain object:

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2']
]);
const obj = Object.fromEntries(map);
console.log(obj); // { key1: 'value1', key2: 'value2' }

Practical Use Cases

Parsing URL Query Parameters

The URLSearchParams interface in browsers returns an iterator that can be directly converted into an object:

const params = new URLSearchParams('name=John&age=30');
const queryObj = Object.fromEntries(params);
console.log(queryObj); // { name: 'John', age: '30' }

Processing Form Data

Collecting form data and converting it into an object structure:

const form = document.querySelector('form');
const formData = new FormData(form);
const formObj = Object.fromEntries(formData);

Data Format Conversion

Converting a two-dimensional array into an object:

const data = [
  ['id', 1],
  ['title', 'ECMAScript 10'],
  ['published', true]
];
const post = Object.fromEntries(data);
console.log(post); // { id: 1, title: 'ECMAScript 10', published: true }

Considerations

  1. Non-string Key Conversion: All keys are coerced into strings.

    const entries = [[1, 'one'], [true, 'true']];
    const obj = Object.fromEntries(entries);
    console.log(obj); // { '1': 'one', 'true': 'true' }
    
  2. Support for Symbol Keys: Starting with ES2019, Symbols are supported as keys.

    const sym = Symbol('description');
    const obj = Object.fromEntries([[sym, 42]]);
    console.log(obj[sym]); // 42
    
  3. Prototype Chain: The resulting object does not inherit additional prototype properties.

    const obj = Object.fromEntries([['__proto__', 'polluted']]);
    console.log(obj.__proto__); // Does not alter the prototype chain
    

Comparison with Other Methods

Compared to manually implementing the same functionality with reduce, Object.fromEntries() is more concise:

// Old way
const entries = [['a', 1], ['b', 2]];
const obj = entries.reduce((acc, [key, val]) => {
  acc[key] = val;
  return acc;
}, {});

// New way
const obj = Object.fromEntries(entries);

Browser Compatibility and Polyfill

For environments lacking support, a polyfill can be implemented as follows:

if (!Object.fromEntries) {
  Object.fromEntries = function(entries) {
    const obj = {};
    for (const [key, value] of entries) {
      obj[key] = value;
    }
    return obj;
  };
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.