Methods for reducing arrays in JavaScript

Is there a way to transform an array of objects into an object with one of the properties as a key?

What is the best method to achieve this conversion?


const data = [
  {
    id: "first",
    name: "Product 1",
    type: "selection"
  },
  {
    id: "second",
    name: "Product 2",
    type: "text"
  },
  {
    id: "third",
    name: "Product 3",
    type: "csv"
  }
] 

Desired output:

{
  first: { name: 'Product 1', type: 'selection' },
  second: { name: 'Product 2', type: 'text' },
  third: {name: 'Product 3', type: 'csv' },

}  

Can this be achieved using the ARRAY.REDUCE METHOD?

Answer №1

test

const details = [
  {
    id: "one",
    name: "Item A",
    category: "selection"
  },
  {
    id: "two",
    name: "Item B",
    category: "text"
  },
  {
    id: "three",
    name: "Item C",
    category: "csv"
  }
] 
const newObj = Object.fromEntries(details.map(val => [val.id, val]));

console.log(newObj);

Answer №2

Take a look at this

const information = [
  {
    id: "first",
    name: "Item 1",
    type: "selection"
  },
  {
    id: "second",
    name: "Item 2",
    type: "text"
  },
  {
    id: "third",
    name: "Item 3",
    type: "csv"
  }
]

const outcome = {};
information.forEach(info=>{
   outcome[info.id] = {
   name: info.name,
    type:info.type
  }
});

Answer №3

Learn how to utilize Array.reduce() with this example:

const data = [
  {
    id: "first",
    name: "Product 1",
    type: "selection"
  },
  {
    id: "second",
    name: "Product 2",
    type: "text"
  },
  {
    id: "third",
    name: "Product 3",
    type: "csv"
  }
];

const result = data.reduce((acc, obj) => {
  const { id, ...rest } = obj;
  acc[id] = rest;
  return acc;
}, {});

console.log(result);

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

Analyze the JSON data retrieved from the API endpoint to determine any

I am currently attempting to utilize axios to send an API request in order to validate login credentials, but I am facing difficulties retrieving the result from the API. The MongoDB .find function successfully locates the correct row, however, I am encoun ...

Implementing event listeners with AngularJS after making a POST request

As I delve into the world of development, please forgive my lack of knowledge. My search for solutions brought me here. I am currently working on a comment and reply app. In order to add comments to my view, I am utilizing this specific function. $scope.i ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

What is the best way to locate the offspring of a parent div using its data attribute?

If I have a container div called dvMainDiv with multiple child divs inside it, all added programmatically, how can I retrieve a specific child div based on its data-id attribute? <div id="dvMainDiv" class="dvMainDiv"> <div id="dvChildDiv" cla ...

Storing Values with RxJava on Android

Currently in the process of learning RxJava. Data Analysis: Variable holding string - command Objective: Utilize split method to separate strings using space as a regular expression - accomplished Verify if array contains elements - completed T ...

Passing data between Service and Component using Angular Binding

I am attempting to show a loading indicator whenever an Http Request is sent. Although I am using Angular's Http Interceptor, the style of the indicator never seems to update. In my app.component.html, I have included a loading indicator. <div ...

Accessing a property that doesn't exist on a union type in Phaser using TypeScript

Currently, I've been immersed in the world of game development with Phaser 3 by following this insightful tutorial at . However, my focus has now shifted towards deploying these games online and adapting the code for use with TypeScript while gearing ...

howler.js resumes playing sprite sound after being paused

I have been working on setting up an audio sprite using Howler.js. The basic functionality of the sprite is working well, but I am facing an issue when trying to resume playback after pausing a sprite. When I call play(), it does not work as expected. sou ...

populate first and then aggregate all the data in mongoose

My goal was to first populate and then aggregate data Comps.find().populate({ path : "reviews", model : "Review" }).exec(function(err, populatedData){ if(err) console.log(err) console.log("populatedData--", populate ...

Verify whether the user's email is registered in the database

I have a login form and I want to verify if a user's email exists in the database, but I'm not sure about the syntax for integrating Angular with Node. In my Main.js file, I have an ng-click on the submit button that triggers this function. I ex ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

Is spine.js truly capable of 'streamlining' POST requests?

I recently came across a post by Alex Maccaw, where he discusses the challenges of sending Ajax requests in parallel: Maccaw explains that if a user creates a record and quickly updates it, two Ajax requests are sent simultaneously - a POST and a PUT. How ...

Slide toggle in jQuery reveals itself briefly before vanishing

Check out the codepen here: https://codepen.io/anon/pen/gRJEwx Essentially, with jQuery toggle 'slide', the div slides in and right back out. It seems to only happen every second or third time the button is pressed. The first try never triggers ...

Exploring the method of retrieving object properties from JSON with BeautifulSoup and Python

from bs4 import BeautifulSoup import fake_useragent import requests ua = fake_useragent.UserAgent() import soupsieve as sv url = "https://search-maps.yandex.ru/v1/?text=%D0%9F%D0%BE%D1%87%D1%82%D0%B0%20%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8,%20%D0%9A%D ...

Updating Button Color Based on Input Field Value in EJS

How can I change the color of a button in EJS when the input value changes? <div> <textarea name="mytextarea" id="inputcontent" cols="30" rows="3" style="margin-top: 10px; margin-bottom: 10px; f ...

Are there any CSS hacks available to address the combination of position: sticky and overflow within the parent element?

I've encountered a sticky position issue when the overflow property is set to auto on a parent element. I've tried various solutions like adding an extra wrapper or using clip instead of auto, but none have worked. While I did find a solution usi ...

Using Json.Net, Object[] can be defined with strong typing

I have encountered an issue that has been bothering me for quite some time. I rely on JSON.Net for serializing and deserializing objects. I use a specific code snippet to call methods based on their parameter types. When I execute the given code, it outpu ...

Utilizing react-router in conjunction with an Express server

Currently, I have a React application that is being served by a basic Express server setup. The React app itself is being compiled with webpack and saved in a folder named "dist" within the root directory, where the server.js file is also located. Inside t ...

Create a submit button using Vue.js for text input

Can anyone help with a beginner question? I have a form that includes a text field. When I type something in and press enter, no result shows up. However, when I type something in and click the button, I get the desired result. Could someone guide me on ...

Raycasting in three.js - mouse pointer and highlighting not precisely aligned with intersected mesh

My current setup involves using a raycaster to highlight a row of cubes arranged in a grid format. The highlighting works fine, but I'm encountering issues with the cursor turning into a pointer precisely over the cubes in the row. Moreover, the highl ...