How to use object. Fromentries() in ES10?

Time:2021-11-30

Author: shade
Translator: front end Xiaozhi
Source: dmitripavlutin

Dream, dry goods, wechat search[move to the world]Pay attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHubhttps://github.com/qq449245884/xiaozhiIt has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

We knowObject.entries()Is to convert an object into an array of key value pairs of its own enumerable properties. Similarly, we can alsoKey value pair arrayTurned into an object.

const keyValuePair = [
  ['cow', '?'],
  ['pig', '?'],
]

Object.fromEntries(keyValuePair);
// { cow: '?', pig: '?' }

 Object.fromEntries

As we know, the object structure is a combination of keys and values, as shown below:

const object = {
  key: 'value',
};

Based on this logic, if we want to turn something into an object, we must pass itKey and value

There are two types of parameters that meet these requirements:

  1. Array with nested key value pairs
  2. Map object

useObject.fromEntriesConvert array to object

Here is a nested array of key value pairs

const nestedArray = [
  ['key 1', 'value 1'],
  ['key 2', 'value 2']
]

useObject.fromEntriesYou can convert the array to an object:

Object.fromEntries(nestedArray);
// { key 1: "value 1", key 2: "value 2"}

useObject.fromEntriesConvert map to object

ES6 brings us amapNew object, which is very similar to the object.

TC39: the mapping object is a collection of key / value pairs, where both keys and values can be any ECMAScript language value.

Let’s create oneMapObject:

//Use constructor
const map = new Map([
  ['key 1', 'value 1'],
  ['key 2', 'value 2']
])

//Or we can use the instance method "set"
const map = new Map()
map.set('key 1', 'value 1')
map.set('key 2', 'value 2')

//Results
Map(2) {"key 1" => "value 1", "key 2" => "value 2"}

Let’s useObject.fromentriestakemapConvert to an object

Object.fromEntries(map);
// { key 1: "value 1", key 2: "value 2"}

Wrong type of object: attempted to useObject.fromEntriesConvert other types to objects

Pass in the following typesObject.fromEntriesWill result in an errorcaught TypeError

How to use object. Fromentries() in ES10?

Make sure that the passed value has a key value pair

Everyone said that there was no project in the resume, so I helped you find a project and attached it[building tutorial]

Object.fromEntries vs Object.entries

Object.fromEntriesyesObject.entriesReverse.Object.entries()Method returns an array of key value pairs of enumerable properties of a given object, andObject.fromEntries()Method converts the list of key value pairs into an object.

const object = { key1: 'value1', key2: 'value2' }

const array = Object.entries(object)
// [ ["key1", "value1"], ["key2", "value2"] ]


Object.fromEntries(array)
// { key1: 'value1', key2: 'value2' }

Object to object conversion

If you readTC39 proposal, which is why this new method was introduced. along withObject.entriesBefore the introduction of, it is troublesome to convert some non object structures into objects.

Usually, when we choose to useObject.entries, because it enables us to access many beautiful array methods, such asfilter。 But after the conversion, we were a little troubled by the array.

const food = { meat: '?', broccoli: '?', carrot: '?' }

// ?  Stuck in this result
const vegetarian = Object.entries(food).filter(
  ([key, value]) => key !== 'meat',
)
// [ ["broccoli", "?"], ["carrot", "?"] ]

ok We can take advantage of all these useful array methods, but we can still return objects. Finally, from object to object conversion?

const food = { meat: '?', broccoli: '?', carrot: '?' }

const vegetarian = Object.fromEntries(
  Object.entries(food).filter(([key, value]) => key !== 'meat'),
)

// { broccoli: '?', carrot: '?' }

Alternatives to converting arrays to objects

Object.fromEntriesIt’s ES10. It’s very new. Maybe the browser support is friendly enough. So let’s look at how to turn an array with a key value pair structure into an object.

Use the reduce method to convert an array into an object

A popular way to convert arrays to objects is to usereduce

const array = [
  ['key1', 'value1'],
  ['key2', 'value2']
]

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2']
])

function toObject(pairs) {
  return Array.from(pairs).reduce(
    (acc, [key, value]) => Object.assign(acc, { [key]: value}),
    {}
  )
}


//Results
// { key1: 'value1', key2: 'value2' }

Use the library to convert arrays to objects

Lodash also provides methods to convert key value pairs into objects.

_.object

Converts an array to an object. transmit[key, value]A single list of pairs, or a list of keys and values.

const array = [
  ['key1', 'value1'],
  ['key2', 'value2']
]

_.object(array)
// { key1: 'value1', key2: 'value2' }
_.fromPairs

_.fromPairsyes_.toPairsIts method returns an object consisting of key value pairs.

const array = [
  ['key1', 'value1'],
  ['key2', 'value2'],
]

_.fromPairs(array)
// { key1: 'value1', key2: 'value2' }

Browser support

How to use object. Fromentries() in ES10?


The bugs that may exist after code deployment cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful bug monitoring toolFundebug

Original text:https://medium.com/@samantham…

communication

Dream, dry goods, wechat search[move to the world]Pay attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHubhttps://github.com/qq44924588…It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

How to use object. Fromentries() in ES10?