Convert a collection of objects into a list of objects, using a specific object property as the key for each item

I am trying to transform an array of objects into an object with keys that are based on one of the properties of each object. For example:

Here is a sample of the original array:

const myArray = [
  {"groupName":"groupname","description":"nice description here","name":"name1","value":107},
  {"groupName":"groupname","description":"nice description here","name":"name1","value":107}
]

While Object.assign comes close to what I need, it assigns numeric keys to the objects like this:

let newObject = Object.assign({}, myArray);

This results in an object like this:

{
  "0": {"groupName":"groupname","description":"nice description here","name":"name1","value":107},
  "1": {"groupName":"groupname","description":"nice description here","name":"name1","value":107}
}

What I really want is for one of the properties to be used as the key instead of numbers, like this:

{
  "name1": {"groupName":"groupname","description":"nice description here","name":"name1","value":107},
  "name2": {"groupName":"groupname","description":"nice description here","name":"name2","value":107}
}

Although I can iterate and create the object manually, I wonder if there is a way to achieve this using ES6 without having to use forEach or map.

Any suggestions?

Answer №1

If you want to change an array into an object with a specific value as a key, you will need to loop through the array and create the properties of the objects.


You can use Array#reduce to add properties to an object manually:

const myArray = [{"groupName":"groupname","description":"nice description here","name":"name1","value":107}, {"groupName":"groupname","description":"nice description here","name":"name2","value":107}]

const result = myArray.reduce((r, o) => (r[o.name] = o, r), {});

console.log(result);

Alternatively


You can also use Array#map to encapsulate each object within an object with a key, and then merge them into a single object using Object#assign along with spread:

const myArray = [{"groupName":"groupname","description":"nice description here","name":"name1","value":107}, {"groupName":"groupname","description":"nice description here","name":"name2","value":107}]

const result = Object.assign({}, ...myArray.map((o) => ({ [o.name]: o }));

console.log(result);

Answer №2

Do we really need to rely on ES6 and complex loops like map/reduce/forEach when simple manipulations can often suffice?

let myArray = [
  {"groupName":"groupname","description":"nice description here","name":"name1","value":107},
  {"groupName":"groupname","description":"nice description here","name":"name2","value":108}
]
let newObject ={};
newObject[myArray[0].name] = myArray[0];
newObject[myArray[1].name] = myArray[1];
console.log(newObject);

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 Adding or Deleting 2 Rows in a Table

When the basket icon on the right is clicked, I want to remove both the current <tr> and the yellow one as well. Check out this screenshot: This is the HTML code for the two rows that need to be deleted with a click: <tr> <t ...

Creating a table from data in your database using Firebase

Can anyone guide me on how to craft a data table similar to this examplehttps://i.sstatic.net/xiUNn.pngusing information from a Firebase database like shown here https://i.sstatic.net/YBzjz.png The table should have columns for ID, Title, Number of Answer ...

What criteria does Angular use to determine when the aot compiler should be utilized?

This page discusses the concept of modules in Angular and explains the two approaches to bootstrapping - dynamic and static. The configuration for these approaches is typically found in main.ts: // Using the browser platform with a compiler import { platf ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Updating device information in real-time using React Native

Currently, I am utilizing react-native-device-info to access the DeviceLocale or DeviceCountry. However, I am wondering if there is a method to update Device-info without requiring a complete restart of the app. For instance, when my device language is se ...

exploring the depths of multidimensional arrays

My array is structured as follows: $arr = array( array('contents' => "any value", 'tags' => '<th>' ), array('contents' => "any value", 'tags' => "< ...

Ways to easily modify images using a single button with the help of jq

I am new to programming and eager to learn... Currently, I am facing the following problem: I would like to create a functionality where three images can be changed using one button and incorporating fadeIn and fadeOut animations. Essentially, all images ...

Vue: Develop a master component capable of displaying a sub-component

Is there a way to design a main component that is able to accept and display a subcomponent? Take the following scenario for instance: <Container> <Item/> <Item/> <SubMenu/> <Btn/> </Container> ...

In React and Node Js, the setState function will return a value of NULL

My Node Js API utilizes a find function to retrieve data from the database, which works flawlessly and returns the results. However, when I pass this data into setState using React and Axios, it ends up returning null. Below is my API's find() functi ...

The Typewriter Effect does not appear alongside the heading

For my portfolio website, I am using React to create a unique typewriter effect showcasing some of my hobbies. Currently, the code is set up like this: "I like to" [hobbies] However, I want it to display like this: "I like to" [h ...

What is the best method to create Promise API synchronously?

When it comes to testing with NodeJS, I rely on selenium-webdriver. My goal is to streamline the selenium-webdriver API by making it synchronous, which will result in more concise tests. The method getTitle() is used to retrieve the title of the current p ...

Tips for maintaining the original Backbone template when reloading the browser

Within my Backbone application (with a Rails backend), I utilize [Handlebars] JavaScript templates (JST's) to render the Backbone views. However, whenever I refresh the browser while on a URL template, it always redirects me back to the root URL. I am ...

What is the best way to modify JSON data within a file?

To start, I retrieve a JSON array by using the following JavaScript code: $.getJSON("myJSONfile.json") .done(function(data) { myData = data; }); After storing the data in myData, which is a global variable, I proceed to add more informati ...

Promise.allSettled() - Improving resilience through retry mechanisms for concurrent asynchronous requests

TL;DR: I'm seeking advice on how to handle multiple promise rejections and retry them a specified number of times when using Promise.allSettled() for various asynchronous calls. Having come across this article: I was intrigued by the following state ...

Experiencing trouble with retrieving the selected image source and showing it in a text field

Looking for help with a javascript issue related to image selection. My goal is to store the selected image's src in a variable and display just the folder ID and image ID without the path and file extension. I want this process to happen in real time ...

Having trouble retrieving returned data after refetching queries using Apollo and GraphQL

I am able to track my refetch collecting data in the network tab, but I am facing difficulty in retrieving and using that data. In the code snippet below where I am handling the refetch, I am expecting the data to be included in {(mutation, result, ...res ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

Obtain URL parameters prior to rendering with Next.js on the server side

Looking to retrieve the parameters from a URL coming from the Spotify API, for example: http//link.com/?code=examplecode. Is there a way to extract the value of "code" prior to rendering so that I can redirect it and transfer the code value to another p ...

Different option to chained promises

In an attempt to develop a function that acquires a presigned s3 URL (call 1) and performs a PUT request to s3, I find myself contemplating the usage of a nested promise structure, which is commonly recognized as an anti-pattern. Outlined in JavaScript/ps ...

"Implementing a click event handler on a button within an iframe

On my website, I have embedded an iframe containing external content. Within the code of this iframe is a button identified by the id "XYZ." I want to create an onclick function for this button. Here's what I've attempted: $( "#XYZ" ).click(fun ...