Object.fromEntries()

Convert an Array of key-value pairs to an Object.

Signature

Object.fromEntries(entries: Array<[String, A]>) => { *: A }

Description

Object.fromEntries() creates an Object from an Array of key-value pairs.

Parameters

Parameter Type Required Description

entries

Array

true

An Array containing nested Arrays of key-value pairs. Each nested Array represents an Object property and should have two elements:

  • 0: A String representing the property key.

  • 1: The property value.

Return value

Type Description

Object

Object with properties from the entries Array.

Examples

Basic example

// Array containing the name and stock quantity
// of various products.
let products = [
  [
    "bananas",
    300
  ],
  [
    "limes",
    200
  ],
  [
    "lemons",
    500
  ]
]

// Convert the Array to an Object.
Object.fromEntries(products)
{
  bananas: 300,
  limes: 200,
  lemons: 500
}

Dynamically assign object keys

You can use Object.fromEntries() to dynamically assign object property keys. For example:

let property1 = "hello"
let property2 = "hi"

let entries = [
  [property1, "world"],
  [property2, "there"]
];

Object.fromEntries(entries);
{
  hello: "world",
  hi: "there"
}

Transform Objects

You can use Object.entries(), Object.fromEntries(), and Array methods to transform objects:

// This query multiplies each Number in an Object
// by 2.

// An object containing various Numbers.
let nums = {
  a: 1,
  b: 2,
  c: 3
}

// Convert the Array to an Object.
let numArray = Object.entries(nums)

// Iterate through the Array, multiplying
// each value and outputting an Object.
Object.fromEntries(
  numArray.map(elem => {
    let key = elem[0]
    let value = elem[1]

    [ key, value * 2 ]
  })
);
{
  a: 2,
  b: 4,
  c: 6
}
\