Object.entries()

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

Signature

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

Description

Object.entries() gets an Object’s properties as Array elements.

You can then iterate through the Array using one of the following methods:

Parameters

Parameter Type Required Description

object

Object containing fields of Any type.

Yes

Object to convert to an Array

Return value

Type Description

Array

Array of the Object’s key-value pairs.

Examples

Basic example

// Object containing the name and stock quantity
// of various products.
let products = {
  bananas: 300,
  limes: 200,
  lemons: 500
}

// Convert the Object to an Array.
Object.entries(products)
[
  [
    "bananas",
    300
  ],
  [
    "limes",
    200
  ],
  [
    "lemons",
    500
  ]
]

Iterate through an Object

You can use the following methods to iterate through the Array returned by Object.entries():

Extending the previous example:

// Object containing the name and stock quantity
// of various products.
let products = {
  bananas: 300,
  limes: 200,
  lemons: 500
}

// Convert the Object to an Array.
let prodArray = Object.entries(products)

// Iterate through the Array.
prodArray.map(product => {
  // Concatenate each product's name and stock.
  product[0] + ": " + product[1].toString()
})
[
  "bananas: 300",
  "limes: 200",
  "lemons: 500"
]

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
}

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!