Object.fromEntries()与Object.entries()

568 阅读2分钟

Object.fromEntries() 介绍

Object.fromEntries()方法是一个静态方法,它接受一个键值对的可迭代对象,并返回一个新的对象。它用于从给定的键值对数组或其他可迭代对象创建一个新的对象。每个键值对数组应该具有两个元素,第一个元素是键,第二个元素是对应的值。

示例:

const entries = [
  ['name', 'John'],
  ['age', 30],
  ['city', 'New York']
];

const obj = Object.fromEntries(entries);
console.log(obj);
// Output: { name: 'John', age: 30, city: 'New York' }

在上面的示例中,我们有一个键值对的数组entries,其中包含了一些属性和对应的值。通过调用Object.fromEntries(entries),我们将数组转换为一个新的对象obj,其中键值对对应了原始数组中的属性和值。

Object.fromEntries()方法对于将键值对数组转换为对象非常有用。它是从ES2019(ECMAScript 2019)开始引入的。

Object.entries() 介绍

Object.entries()方法是一个静态方法,它返回一个给定对象自己的可枚举属性的键值对数组。返回的数组中每个元素都是一个形如[key, value]的数组,其中key是属性名,value是对应的属性值。

示例:

const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const entries = Object.entries(obj);
console.log(entries);
// Output: [['name', 'John'], ['age', 30], ['city', 'New York']]

上面的示例中,我们有一个包含一些属性和对应的值的对象obj。通过调用Object.entries(obj),我们将这个对象转换为一个键值对的数组entries,其中每个元素都是一个包含属性和值的数组。

Object.entries()方法非常有用,可以让我们轻松地迭代对象的属性和值。我们可以在for...of循环中使用它,或者使用其他数组方法对键值对数组进行操作。这个方法在ES2017(ECMAScript 2017)中被引入。

Object.fromEntries()的Polyfill

if (!Object.fromEntries) {
  Object.fromEntries = function(entries) {
    if (!entries || !entries[Symbol.iterator]) {
      throw new TypeError("Object.fromEntries() requires an iterable argument");
    }

    const obj = {};

    for (const [key, value] of entries) {
      obj[key] = value;
    }

    return obj;
  };
}

Object.entries()的Polyfill

if (!Object.entries) {
  Object.entries = function(obj) {
    if (obj !== Object(obj)) {
      throw new TypeError('Object.entries called on non-object');
    }

    const entries = [];

    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        entries.push([key, obj[key]]);
      }
    }

    return entries;
  };
}