Transforming an array of JavaScript objects into arrays of key-value pairs based on a specific property with ES6 syntax

Consider an array of objects like this:

myArray = [
  {name: 'First', parent: 1, delta: 2},
  {name: 'Second', parent: 1, delta: 1},
  {name: 'Third', parent: 2, delta: 1}
];

The goal is to transform this array into an object with parent keys and corresponding values. For example:

result = {
  1: [
       {name: 'First', parent: 1, delta: 2},
       {name: 'Second', parent: 1, delta: 1}
     ],
  2: [
       {name: 'Third', parent: 2, delta: 1}
     ]
}

To achieve this using a concise ES6 syntax that allows for operations such as sorting by delta, we can explore alternative methods beyond traditional loops.

Answer №1

If you need to group elements by a specific key, you can utilize the Array.reduce() method like this:

let items = [{
    name: 'First',
    type: 1,
    value: 2
  },
  {
    name: 'Second',
    type: 1,
    value: 1
  },
  {
    name: 'Third',
    type: 2,
    value: 1
  }
];
var groupedItems = items.reduce((acc, item) => {
  if (acc[item.type]) {
    acc[item.type].push(item);
  } else {
    acc[item.type] = [item];
  }
  return acc;
}, {});
console.log(groupedItems);

Answer №2

To accomplish this task, you have the option of utilizing the reduce method.

var data = [
  {name: 'First', parent: 1, delta: 2},
  {name: 'Second', parent: 1, delta: 1},
  {name: 'Third', parent: 2, delta: 1}
];

var output = data.reduce((obj, item) =>
             (
               obj[item.parent] = (obj[item.parent] || []).concat(item)
               , obj
             )
             , {})
console.log(output)

Answer №3

let animals = [
  {species: 'Lion', habitat: 'Savannah', status: 'Endangered'},
  {species: 'Giraffe', habitat: 'Grasslands', status: 'Vulnerable'},
  {species: 'Elephant', habitat: 'Forest', status: 'Threatened'}
];

console.log(animals.reduce((acc, val)=>({...acc, [val.habitat]: (acc[val.habitat] || []).concat(val)}), {}))

Answer №4

let groupedArray = myArray.reduce((grouped, element) => {
  if (grouped[element.parent]) grouped[element.parent].push(element);
  else grouped[element.parent] = [element];
  return grouped;
}, {});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a Problem with Chart.js Library During Online Tutorial on YouTube

Currently, I am immersed in a YouTube tutorial that guides me through the process of creating an expense tracker application. However, as I diligently follow the steps outlined in the tutorial, I encounter a hiccup along the way. Instead of witnessing the ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Are arrays being used in function parameters?

Can the following be achieved (or something similar): function a(foo, bar[x]){ //perform operations here } Appreciate it in advance. ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

Leveraging the power of jQuery and vanilla JavaScript to create a pop-up print window for a Div element within a CMS platform that does not support media query stylesheets

I have been grappling with this particular issue for weeks now, seeking guidance from previous inquiries here. Yet, despite the helpful hints, I am still struggling to find a viable solution. My website features a scrolling sidebar measuring approximately ...

Is there a way to retrieve the name of a document stored within a collection using Firebase Firestore and Firebase Storage

When fetching data from the 'users' collection in Firebase Firestore and mapping the response, I have a function that converts the array of domains and filters out any domains that do not meet certain criteria. Here's an example: Sample dom ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

What causes the Cassandra client driver to provide more detailed information compared to cqlsh?

I'm currently utilizing the datastax nodejs-driver to retrieve information about a keyspace from cassandra. const results = await client.execute( ` DESC KEYSPACE ${keyspace} ` ); The method client.execute provides a comprehensive object containin ...

What is the best way to dynamically implement text ellipsis using CSS in conjunction with Angular 7?

i need to display a list of cards in a component, each card has a description coming from the server. In my component.html, I am using a ngFor like this: <div [style.background-image]="'url('+row.companyId?.coverUrl+')'" class="img- ...

Utilizing clip-path polygons for effective styling on Firefox and iOS

I have been working on a plugin to create animated modal boxes by utilizing the clip-path property. However, I have encountered an issue where this code only seems to work in Chrome. You can view the codepen demo here. Unfortunately, it appears that Firef ...

What sets Redux React-Native apart: Exploring the nuances between utilizing useSelector in react-redux versus connect

I believe they were identical because both extracted the content from the store. What could potentially differentiate them? ...

Nonconforming Typescript argument specification

I've been struggling to pass this TypeScript array to a function. Despite trying multiple parameter types in an attempt to get it to compile, none of them have worked so far. Here is the array in question: var driverTally = [ { dr ...

Adding a C# variable to a URL in a Razor view using jQuery

My Razor page looks like this: @{ ViewData["Title"] = "mypage"; string ApiAddress = "https://localhost:8114/api/"; } <div> ... </div> @section Scripts{ <script> functio ...

Location of Ajax callback function

I encountered an issue with a callback function that was placed within $(document).ready. The callback function wasn't functioning as expected. Surprisingly, when I moved it outside of $(document).ready, the code started working flawlessly. I am puzzl ...

The JSON output is throwing an error because it is unable to access the property '0' since it is

Trying to convert JSON data into an HTML table, I encountered the following error: "Cannot read property '0' of undefined" <?php $idmatchs = "bGdzkiUVu,bCrAvXQpO,b4I6WYnGB,bMgwck80h"; $exploded = explode(",", $idmatchs); $count = count( ...

The use of jquery's split() and indexOf functions may lead to the error message "Property or method not supported by the object."

Below is the code snippet I am working with: var selected = $('#hiddenField').val().split(","); ... if (selected.indexOf(id) > 0) { ... set value ... } In my ongoing task of dynamically creating a CheckBoxList, I am attempting to retain t ...

Error encountered while trying to update a record using NodeJS, Express, and MySQL modules due to SQL syntax

When attempting to update a MySQL record in NodeJS, I encounter an "app crashed" error in Visual Studio Code's terminal. app2.js: const express = require('express'); const mysql = require('mysql'); // establish connection cons ...

Utilizing Express and ejs to display a JSON using the "<%" tag

I am facing an issue with the code in my index.ejs file. The current code snippet is as follows: var current_user = <%= user %> In my node.js file, I have the following code: app.get("/", function(req, res){ res.locals.user = req.user res. ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

AngularJS issue: Radio buttons failing to select multiple options

I developed a cross-platform app using AngularJS, Monaca, and Onsen UI. The app reads a nested JSON object and displays the items in a list format. The main items act as headings, while the sub-items are displayed as radio buttons like this: - Apples -- ...