Retrieve an object from an array containing multiple objects

In my current project, I am working with an array of objects that look like this:

const values = [
    {
      clientType: "Client Type 1",
      value: 130
    },
    {
      clientType: "Client Type 2",
      value: 10
    },
    {
      clientType: "Client Type 3",
      value: -80
    },
    {
      clientType: "Client Type 4",
      value: -52
    }
  ]

My goal is to transform and group this array into a single object as shown below:

results = {
  "Client Type 1": 130,
  "Client Type 2": 10,
  "Client Type 3": -80,
  "Client Type 4": -52,
}

I am wondering if there is a direct way to achieve this using just one map function? Any insights would be greatly appreciated.

Thanks in advance.

Answer №1

const data = [
    {
      customerType: "Customer Type A",
      amount: 130
    },
    {
      customerType: "Customer Type B",
      amount: 10
    },
    {
      customerType: "Customer Type C",
      amount: -80
    },
    {
      customerType: "Customer Type D",
      amount: -52
    }
  ]
  
const finalResult = data.reduce((total, {customerType, amount}) => ({ ...total, [customerType]: amount}), {})

console.log(finalResult)

Answer №2

For this straightforward question or task, I will provide a clear and easy-to-understand solution.

const values = [{
      clientType: "Client Type 1",
      value: 130
    },
    {
      clientType: "Client Type 2",
      value: 10
    },
    {
      clientType: "Client Type 3",
      value: -80
    },
    {
      clientType: "Client Type 4",
      value: -52
    }
  ],
  // Iterate through the "values" object to create an object in the required format and return it.
  resultObj = values.reduce((a, c) => {
    // a: represents the object being constructed, initially empty {}
    // c: the current object from the "values" array
    a[c.clientType] = c.value;
    return a;
  }, {});

// This line is optional and just logs the result to the console
console.log(resultObj);

A quick note (but significant), you can only access an attribute on the resulting Object using bracket notation:

resultObj['Client Type 1'] // prints: 130

Find out more about the reduce method on MDN.

Answer №3

After some tinkering, I managed to get this code working smoothly:

const items = [
{
  product: "Product A",
  price: 200
},
{
  product: "Product B",
  price: 50
},
{
  product: "Product C",
  price: -30
},
{
  product: "Product D",
  price: -15
}
  ]

items.map(displayInfo);

function displayInfo(item) {
  return [item.product,item.price].join(" ");
}

Answer №4

Give this a shot:

const data = [
  {
    type: "Type A",
    amount: 150,
  },
  {
    type: "Type B",
    amount: 20,
  },
  {
    type: "Type C",
    amount: -70,
  },
  {
    type: "Type D",
    amount: -42,
  },
];

const outcome = {};
for (let i = 0; i < data.length; i++) {
  outcome[data[i].type] = data[i].amount;
}

console.log("data", data);
// data [
//     { type: 'Type A', amount: 150 },
//     { type: 'Type B', amount: 20 },
//     { type: 'Type C', amount: -70 },
//     { type: 'Type D', amount: -42 }
//   ]

console.log("outcome", outcome);
//   outcome {
//     'Type A': 150,
//     'Type B': 20,
//     'Type C': -70,
//     'Type D': -42
//   }

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

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

The HTML5 postMessage function often returns an undefined value

My attempt to establish cross-domain communication using postMessage between a page hosted on example1.com and an iframe within the same page on example2.com is facing some challenges. Once the iframe finishes loading, it sends a postMessage to the parent ...

Displaying a binary PDF file in a web browser using JavaScript

I am facing an issue with displaying files from a MSSQL Server Database that are stored as a column Content of type VARBINARY(MAX) in a SQL table. To access the database, I have developed a backend Node.js server using Express.js. There is a route called ...

php How can an array be empty?

Here is my code snippet that aims to keep track of selected items and display them from an array: <?php session_start(); //temp stores the submitted value $temp = $_POST['field']; if (!isset($_SESSION['itemsList'])) { $itemsLi ...

What is the best way to temporarily bold a cell item within a table row for a specified duration of time?

I am experiencing an issue with a section of my code where I am fetching values from the server and updating a table if a certain value is not present. Once the update is made, I want to visually notify the user by temporarily making the cell's value ...

Adding a child element in older versions of Internet Explorer browsers using

I am facing an issue where my JavaScript code breaks in old IE browsers while trying to create a new element and append it to another element using the appendChild function. var child = document.createElement('span'); child.innerHTML = "Hello Wo ...

Displaying historical data on hover in a chart using Vue3 and Chart.js

Displaying previous data on hover in Vue3 Chart JS After updating my chart data with API information, I encountered an issue where the chart would display the previous API data when hovering over it. I attempted using distory() but it did not resolve the ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

Is there an easy method to transmit JSON information by utilizing $window.open() with angularjs?

equivalent to unraveling a knot: var data = { name: 'name', info:{ info1: 'uvbiuonns', info2: 'aisbsiece', } } this approach eliminates the need to retrieve data from the server for the popup ...

Guide to rendering JavaScript with pug/jade

Let's say I pass the user variable to this Pug file and I'd like to execute some JavaScript code after the DOM has finished loading. script. document.addEventListener("DOMContentLoaded", function(event) { console.log(#{user.name});/ ...

What is the best way to transfer an excel file to a server using AngularJS in a Django project?

I am experiencing an issue with uploading a file to the server. The variable files in the for loop is showing up as undefined during debugging. Please review the directive to ensure it is correct. HTML <input type="file" accept=".xlsx" file-model/> ...

Manipulate values within an array when a checkbox is selected or deselected

I am developing an Angular application where I have created a checkbox that captures the change event and adds the checked value to an array. The issue I am facing is that even if the checkbox is unchecked, the object is still being added to the array. D ...

Tips for appending a struct to an existing byte array in C++

I have encountered various methods for converting a struct to a byte array by creating a new byte array in the process. However, I am interested in finding a way to achieve this without having to create a new byte array. My message buffer is of size byte[ ...

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

Modify the background color of a pseudo-element's property value dynamically

How do I change the background color of my burger menu by clicking on an icon? This is the CSS code I have: :root{ --pseudo-backgroundcolor: yellow; } .menu__icon span, .menu__icon::before, .menu__icon::after{ background: va ...

Retrieve ALL information from a third-party API request with a limit of 1000 calls

Challenge: Implementation of a third-party API call using Node.JS. The API link restricts the number of users per call to 1000, with an option to retrieve the next set by passing parameters in the URL (?firstResult=1001&maxResults=1000&orderBy=NAME ...

Troubleshooting: ReactJS- Bootstrap Value Issue Not Displaying When Changing Tabs

I am currently working on a React App and utilizing react-bootstrap for development. However, I am encountering an issue where the content is only displaying correctly on the default nav item upon page refresh. When I switch to another nav item, the cont ...

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...

Is there a method to divide an Array based on a specified filter criteria?

Currently, I am facing a challenge with an array that needs to be split into two separate arrays. One array should only hold prices, while the other should only contain descriptions. Here is an example: var startingArray = ["apple", "30.00", "pizza", "2. ...

A guide on managing file uploads in Next.js with the help of Formidable

I'm currently working on a project with Next.js and I'm trying to implement file uploads. I am using the formidable library to handle file uploads on the server side, but I'm facing some issues. Whenever I try to upload a file, I receive a ...