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

What is the procedure for verifying the type of an element using chai?

Is there a way to determine if an element is either an "a" tag or a "div" tag? I've tried the following code, but it's not working as expected: it('has no link if required', () => { const wrapper = shallow(<AssetOverlay a ...

Customizing content based on Route - Utilizing Node.js/React

I am currently working on setting up routes for different pages of store profiles in my Node app. I have been doing some research online and have come to understand how to adjust the parameters, but I am struggling with figuring out how to dynamically chan ...

Create a dynamic select2 field based on the value selected in another dropdown menu

Starting with an initial dropdown where a value needs to be selected: <select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;"> <option value='' selected>Choose an Index</option> ...

Updating div content dynamically with Jquery and PHP variable

How can I continuously update a div with the current date and time using PHP variable and Jquery? Here is my PHP file containing the variable date: <?php $date = date('d/m/Y H:i:s'); ?> And here's the code in my HTML file: <!DOCT ...

JavaScript's setAttribute function is not functioning as expected

I have been using the setAttribue method as shown below. It works perfectly for the first instance, but after that, when I try to change the value, it displays an alert without updating with document.getElementById("to").setAttribute("value", selValue); d ...

How to manage multiple items within a single MUI/React TextField

Recently diving into the world of JS, React, and MUI, I find myself faced with a challenge involving a MUI TextField that is supposed to handle multiple values. For example: 1*10 5*50 13*250 5*50 1*10 3*33.33 4*25 3*33.33 All on a single line. These ...

What could be causing the readTextFile function to return undefined?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; function readFile(file) { let fileContents = new XMLHttpRequest(); fileContents.open("GET", file, false); fileContents.onreadystatechange = function () { ...

Node.js allows for keeping pipe and sockets open even after streaming an HTTP response

My current challenge involves streaming data from an HTTP response to a cloud storage provider within an internal service. const response = await request<Readable>({ headers: httpOpts?.headers, data: httpOpts?.data, url, method, responseTyp ...

specialized registration process with auth0 in Angular

I am attempting to enhance the user information in a single call. The process involves first signing up with a username and password on Auth0, followed by adding additional userinfo to the database during the callback phase. However, I am encountering diff ...

The npm package for google-spreadsheet.js is experiencing issues and is not functioning correctly when trying to replicate the GitHub

After attempting to implement the basic example code provided at https://github.com/theoephraim/node-google-spreadsheet, I encountered an issue. For instance: const { GoogleSpreadsheet } = require('google-spreadsheet') const creds = require(&apo ...

Access an attribute using slashes in Jquery

I've been struggling to use jQuery to select an object based on a unique filename attribute. However, I'm facing issues with escaping slashes when the selector is created using a variable. Despite spending hours trying different combinations, I s ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

Asynchronous functions return objects that transform into '[Object]' representations

I am in the process of setting up a server using Node and Express. In one of my GET routes, I have an asynchronous function that successfully returns the desired data. However, when I attempt to incorporate this data into an object to provide all the neces ...

Retrieve all records from the query and store them in an array, then output a singular value

Retrieve all rows from the database based on a specific query and return a single value Query the database for data //---------------------------------------------------------------------- $result = mysql_query("SELECT * FROM $tableName"); query ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Transferring data from AJAX to PHP

I am currently developing a project in PHP. I have created an associative array that functions as a dictionary. Additionally, I have a string containing text with placeholders for keys from the array. My goal is to generate a new String where these key wor ...

Is there a way to deliver information to a specific element on a client's HTML page?

My current project involves using Node.js to serve a webpage that collects user inputs and stores them in a mongodb server. The web page also displays these user inputs. I am trying to determine the best way to pass the user inputs from node.js to the < ...

Unable to establish a connection with the default port on Mongo DB while utilizing Node.js

I am new to using Node.js and I'm trying to establish a connection with MongoDB in my Node.js application, but I'm encountering issues. Here is the code snippet: var mongo = require("mongodb"); var host="127.0.0.1"; var port=mongo.Connection.DE ...

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...