Skip to content

JavaScript reduce array of objects | Example code

  • by

Using Array forEach, you can reduce array of objects into object in JavaScript. Same thing you can do with Using Array reduce function.

JavaScript reduce array of objects

Simple example code.

Using Array#forEach.

<!DOCTYPE html>
<html>
<body>

  <script>
    data = [
    { name: 'foo', type: 'fizz', val: 9 },
    { name: 'boo', type: 'buzz', val: 3 },
    { name: 'bar', type: 'fizz', val: 4 },
    { name: 'car', type: 'buzz', val: 7 },
    ];
    res = {};
    data.forEach(v => res[v.val] = v.name);

    console.log(res);

  </script>

</body>
</html> 

Using Array#reduce.

<script>
    data = [
    { name: 'foo', type: 'fizz', val: 9 },
    { name: 'boo', type: 'buzz', val: 3 },
    { name: 'bar', type: 'fizz', val: 4 },
    { name: 'car', type: 'buzz', val: 7 },
    ];
    res = data.reduce(function(s,a){
      s[a.val] = a.name;
      return s;
    }, {});

    console.log(res);

</script>

Output:

JavaScript reduce array of objects

How to reduce array of objects into one object?

Answer: Use Array.map() to create an array of [country, object] pairs, and convert it to an object using Object.fromEntries():

Take an array of objects and return an object with the keys of countryName and the value being an object with the rest of the country data

<!DOCTYPE html>
<html>
<body>

  <script>
    var countries = [
    {
      "countryCode": "AF",
      "countryName": "Afghanistan",
      "population": "29121286",
      "capital": "Kabul",
      "continentName": "Asia"
    },
    {
      "countryCode": "AL",
      "countryName": "Albania",
      "population": "2986952",
      "capital": "Tirana",
      "continentName": "Europe"
    },
    {
      "countryCode": "DZ",
      "countryName": "Algeria",
      "population": "34586184",
      "capital": "Algiers",
      "continentName": "Africa"
    },
    ]
    const keyByWithoutKey = (arr, key) => Object.fromEntries(
      arr.map(({ [key]: prop, ...o }) => [prop, o])
      )

    const result = keyByWithoutKey(countries, 'countryName')

    console.log(result)

  </script>

</body>
</html> 

Output:


{
  "Afghanistan": {
    "countryCode": "AF",
    "population": "29121286",
    "capital": "Kabul",
    "continentName": "Asia"
  },
  "Albania": {
    "countryCode": "AL",
    "population": "2986952",
    "capital": "Tirana",
    "continentName": "Europe"
  },
  "Algeria": {
    "countryCode": "DZ",
    "population": "34586184",
    "capital": "Algiers",
    "continentName": "Africa"
  }
}

Do comment if you have any doubts or suggestions on this JS reduce topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading