Transform an array of objects into one unified object

Suppose you have an array like this -

[
  {
    name: "abc",
    value: "1"
  },
  {
    name: "xyz",
    value: "2"
  },
  {
    name: "abc",
    value: "3"
  },
  {
    name: "abc",
    value: "4"
  },
  {
    name: "xyz",
    value: "5"
  },
]

The goal is to transform this array into a single object where values with the same names are grouped together in an array. The desired output should look like this -

{
  abc: [1, 3, 4],
  xyz: [2, 5]
}

How can we achieve this using the reduce method in JavaScript?

I attempted a solution, but it didn't produce the expected result. Here's what I tried:

const data = arr.reduce((acc, item) => {
  return {
    ...acc,
    [item.name]: [item.value, acc[item.value]]
  };
});

Answer №1

Great effort on your answer, but it's important to ensure that acc doesn't already have a key corresponding to item.name:

const data = [{
    name: "abc",
    value: "1"
  },
  {
    name: "xyz",
    value: "2"
  },
  {
    name: "abc",
    value: "3"
  },
  {
    name: "abc",
    value: "4"
  },
  {
    name: "xyz",
    value: "5"
  },
]

const result = data.reduce((acc, { name, value }) => ({
  ...acc,
  [name] : [...(acc[name] || []), value]
}), {})

console.log(result)

Remember, using object destructuring can help simplify the accumulation code.

Answer №2

const data=[
  {
name: "123",
value: "7"
  },
  {
name: "456",
value: "8"
  },
  {
name: "123",
value: "9"
  },
  {
name: "123",
value: "10"
  },
  {
name: "456",
value: "11"
  },
];

const result=data.reduce((accumulator,current)=>{
 (accumulator[current.name]??=[]).push(current.value);
 return accumulator;
},{});
console.log(result);

Answer №3

const information = [{
    title: "abc",
    number: "1"
  },
  {
    title: "xyz",
    number: "2"
  },
  {
    title: "abc",
    number: "3"
  },
  {
    title: "abc",
    number: "4"
  },
  {
    title: "xyz",
    number: "5"
  },
];

let resultObject = {};

information.forEach((element) => {
   if (!resultObject.hasOwnProperty(element.title)) {
      resultObject[element.title] = [element.number];
   } else {
      resultObject[element.title].push(element.number);
   }
});
console.log(resultObject);

Simply convert values from string to number for the desired output

{
  abc: [1, 3, 4],
  xyz: [2, 5]
}

Answer №4

If you want to group the array elements, you can utilize the Array.prototype.reduce method.

const 
  items = [
    { name: "apple", price: "$1" },
    { name: "banana", price: "$2" },
    { name: "apple", price: "$3" },
    { name: "apple", price: "$4" },
    { name: "banana", price: "$5" },
  ],
  groupedItems = items.reduce((grouped, item) => ((grouped[item.name] ??= []).push(item.price), grouped), {});

console.log(groupedItems);

reduce may seem intimidating at first, but with practice, it becomes quite straightforward. Another way to group the array is by using a simple for...of loop.

const items = [
  { name: "apple", price: "$1" },
  { name: "banana", price: "$2" },
  { name: "apple", price: "$3" },
  { name: "apple", price: "$4" },
  { name: "banana", price: "$5" },
];

const groupedItems = {};
for (let element of items) {
  (groupedItems[element.name] ??= []).push(element.price);
}

console.log(groupedItems);

Additional resources for reference:

Answer №5

Implement reduce():

const fruits = [
  {
    type: "apple",
    quantity: "10"
  },
  {
    type: "banana",
    quantity: "5"
  },
  {
    type: "apple",
    quantity: "15"
  },
  {
    type: "orange",
    quantity: "8"
  },
]

const inventory = fruits.reduce((total, current) => ({...total, [current.type]: total[current.type] ? [...total[current.type], current.quantity] : [current.quantity]}), {})
console.log(inventory)

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

Utilizing Linq for Data Consolidation

In my code, I am currently combining two arrays using an identifier array called seqNum2. However, I am facing difficulties with incorporating a third array, grossNGL2, into the mix using Linq. The code works perfectly without grossNGL2, but it is essentia ...

Transferring and giving back two-dimensional arrays in C++

Just starting out with c++ and I've come up with this block of code. #include <iostream> using namespace std; int** mat_mult(int mat1[2][2], int mat2[2][2]){ int mat3[2][2] = {{0,0},{0,0}}; for(int i(0);i<2;i++){ for(int j(0 ...

Fixing event listener problem in ReactJS

const ControlPanel = ({ mainSectionRef }) => { const [canMove, setCanMove] = useState(false) const classes = useStyles(); const toolbarRef = useRef(); const onMouseMove = function (e) { const { x, y } = getMouseCoordinatesOnCanv ...

Tips for retrieving data in PHP using an AJAX jQuery request

After following all the advice on how to make a jQuery or Javascript AJAX request to a php file on a server, I encountered an issue with the response. The response I'm getting is: Fatal error: Array callback has to contain indices 0 and 1 in Her ...

Exploring ways to access an element's background color through JavaScript

Is there a way to access an element's CSS properties that are set by a class name in JavaScript? In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's b ...

Challenges in integrating callbacks effectively in node.js scripts

I am currently working on a node.js function called process() that is meant to return a value when it is invoked. However, I am encountering difficulties in creating a callback for the process(). The expected behavior is for the value to be returned from p ...

Sending the `<path>` wrapped in quotes to `<SvgIcon>` is resulting in the SVG not rendering

When I try to use the Material-UI's SvgIcon component, the <path> element is surrounded by quotes, which is preventing the SVG from rendering properly. https://i.stack.imgur.com/InDRt.png I'm currently working in Storybook within an MDX f ...

Can someone provide a clarification on the meaning of this Javascript code snippet?

I stumbled upon the code snippet below: let customHandler; clearTimeout(customHandler); customHandler = setTimeout(() => {...}); This code example is actually part of a Vue application and consists of the following method: public handleMultiSelectIn ...

Utilizing jQuery post method to retrieve the id_user attribute value

In order to retrieve the data for id_user from a specific row in the table by using onclick jquery, we need to pass the obtained id_user data to the controller and redirect the page to edit_user. How can I fetch the id_user data using the onclick method w ...

What is the best way to make the sidebar occupy the entire space?

Learn about creating sticky footers using this method and check out an example here. * { margin:0; } html, body { height:100%; } #wrap { min-height:100%; height:auto !important; height:100%; margin:0 0 -47px; } #side { float:left; backgro ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

What is the best way to extract data from a JSON file using Java?

I am working with a JavaScript file that contains the following object: var MoceanSettings={ BannerURL:'', IsDirectWall:true, AppOfDayZone:156431, ImpressTrackUrl:null, ClickTrackUrl:null, Categories:[ ...

converting database query results to a PHP array

Trying to implement a dynamic Morris area chart, The SQL query results are as follows: period | item | amount ------ | ---- | ------ 20170801 | iphone | 327 20170801 | ipad | 278 20170801 | ipod | 125 20170802 | iphone | ...

Setting the overlay video to match the input video size in FFMPEG

Currently, I am incorporating FFMPEG wasm into a NextJS project. However, I believe that general FFMPEG solutions will suffice since FFMPEG wasm is capable of interpreting standard FFMPEG commands. My objective is to superimpose an overlay video onto the ...

Is there a way to transform a complex nested class object into a simple object without losing its methods

Is there a way to convert a deeply nested class object into a plain Object type while still retaining methods like getters and setters? class A { id = ""; data = { sync: {} }; } class SyncService { syncResultServiceA = { ...

Resolving conflicting event handlers within vue.js

I have a situation where I'm trying to use two buttons on a page to navigate to different sections. When I include only one button, everything works fine. But when I include both buttons, only one of them functions properly. Upon debugging, I noticed ...

Instructions for setting a cookie to conceal a notification bar upon the second page load

I am looking for the following scenario: When a new visitor lands on my website, a notice bar fixed to the bottom of the screen becomes visible. After clicking on a menu item to navigate to another page, a cookie is set upon the second page load. This co ...

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...

How to mimic preg_replace functionality in JavaScript

Can JavaScript be used to achieve the same outcome? preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $f['logo']); UPDATE - I am encountering an error with this snippet of code: unterminated string literal $('#feed&apo ...

Efficiently flattening an array in JavaScript using recursive functions without the need for loops

Currently I am studying recursion and attempting to flatten an array without using loops (only recursion). Initially, I tried the iterative approach which was successful, but I am facing challenges with the pure recursive version: function flattenRecurs ...