Convert an array of objects into an object where the keys are determined by the value of a specific

I'm working with an array that looks like this:

const inventory = [
  { fruit: 'apple', quality: 'good', quantity: 10 },
  { fruit: 'banana', quality: 'average', quantity: 5 },
  { fruit: 'orange', quality: 'excellent', quantity: 12 },
];

If I want to retrieve information about the "banana" entry, I currently use:

inventory.find(item => item.fruit === 'banana')

However, I'd prefer to access it associatively, like this:

inventory.banana.quantity

To achieve this format, I need to transform my array into an object. I am looking for a simple ES6 solution or possibly utilizing Lodash. Any suggestions?

Answer №1

const exampleObject = [{
    category: 'apple',
    type: 'fruit',
    price: 1
  },
  {
    category: 'banana',
    type: 'fruit',
    price: 3
  },
  {
    category: 'orange',
    type: 'fruit',
    price: 8
  },
];

const result = exampleObject.reduce((accumulator, current) => {
  accumulator[current.category] = current;
  return accumulator
}, {})

console.log(result)

Answer №2

Utilizing Object.fromEntries allows for the creation of the object, with destructuring aiding in extracting the key from the remaining parts of the initial object:

const example = [
  { identifier: 'apple', x: 'y', z: 1 },
  { identifier: 'banana', x: 'm', z: 3 },
  { identifier: 'orange', x: 'n', z: 8 },
];

let outcome = Object.fromEntries(example.map(({identifier, ...remaining}) => [identifier, remaining]));

console.log(outcome);

Answer №3

To implement the _.keyBy() method from lodash, follow this example:

const sampleData = [
  { id: '123', name: 'John' },
  { id: '456', name: 'Jane' },
  { id: '789', name: 'Doe' },
];

const result = _.keyBy(sampleData, 'id');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

Is there a method to modify the arrangement in which 3 specific HTML elements are displayed (i.e., their hierarchy in relation to one another)?

I have 3 "p" elements and I'm trying to find a way to change the order in which they load on the page using JS or CSS. Below is an example of what I've attempted so far. When you click on the first box labeled "about 1," it opens up and displays ...

A JavaScript function that produces an array as an output

Could anyone explain why the output vector from the function TriangulosParaLinhas is not being stored in the vector Lines? if (lineMode == true) { var lines = triangulosParaLinhas(vertices); } function triangulosParaLinhas(vertices) { var poi ...

Encountered a problem while attempting to remove node version

When I run the command nvm ls -> v4.3.2 system default -> 4.3.2 (-> v4.3.2) node -> stable (-> v4.3.2) (default) stable -> 4.3 (-> v4.3.2) (default) iojs -> N/A (default) Upon running nodejs --version, it returns v0 ...

The button similar to Facebook does not function properly when using fancybox

My photo gallery uses fancybox, and when fancybox is open a like button appears outside the title. However, the Facebook like button doesn't seem to work. Here is my JavaScript code: $(".fancyboxi").fancybox({ padding: 0, openE ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

When using jQuery and Laravel, why does the element not appear when setting its display to block after receiving a response?

Trying to handle data (id) retrieved from the database and stored in a button, which appears in a modal like this: There are buttons for "Add" and "Remove", but the "Remove" button is hidden. What I want to achieve: When the user clicks on the "Add" but ...

Loading Ajax content into div (Wordpress) without pre-loading the font can cause display issues

Currently, I'm implementing a JavaScript function within Wordpress using Ajax to load the content of a post into a modal div when specific elements are clicked. Here is an example of how the JS function appears: function openProjectModal($that) { ...

Steps to resolve the error message "The port 9876 has no listening server when karma is running"

I have a situation where I am executing the following code: PS D:\app> karma run However, an error is being displayed: [2013-11-29 17:39:54.297] [DEBUG] config - Loading config D:\app\karma.conf.js There is no server listening on port ...

Validation of decimal numbers in JavaScript without the presence of any other characters

Looking to create a JavaScript regex to validate an 8-digit number that may include decimals. The current regex /^\d+$/ allows for any other characters such as ( , * $ etc. How can I modify this to only accept numbers and periods? For example, the nu ...

The custom tooltip is not being displayed as intended

I'm currently working on customizing tooltips in angularjs google charts. My goal is to display multiple series data along with some text within the tooltip, similar to the demo showcased here. Specifically, I aim to include the legend and title of th ...

Dealing with a 404 Error in Node.js and Express Routing

After successfully creating a Node/Express app tutorial earlier, I encountered issues when trying to replicate it for a new project on both Ubuntu and Windows. The basic routing consistently fails and results in 404 errors, which is incredibly frustrating! ...

A Foolproof Method to Dynamically Toggle HTML Checkbox in ASP.NET Using JavaScript

Although there have been numerous inquiries related to this subject, I haven't been able to find a solution specific to my situation. I currently have a gridview that contains checkboxes. What I'm trying to achieve is that when I select the chec ...

Issue encountered while attempting to load bootstrap in NodeJS

I encountered an error while running my jasmine test case in node. The error message says that TypeError: $(...).modal is not a function. This error pertains to a modal dialog, which is essentially a bootstrap component. To address this issue, I attempted ...

Transforming the output of a PHP script from an HTML table into an ion-list format tailored for the Ionic framework

Currently I am working on an application built with the Ionic framework. I have developed a PHP file to retrieve 'Users' data from my database and it is currently being displayed in an HTML table format. In the services section of the framework, ...

Is the API providing a response in the form of an HTML document

I just created a cutting-edge React application that leverages the power of "fetch" to fetch data from an API. Within my App component in the "App.js" file, you can find the following code snippet: function fetchData() { fetch(`WORKINGURLWITHAPIKEY`) ...

Your request was denied by the Google Maps API server due to an invalid request. Please include the 'size' parameter in your request

I need to incorporate a static Google Map into my application built on node.js. Here is the code snippet: .panel.panel-primary .panel-heading h2.panel-title On the map .panel-body img.img-responsive.img-rounded(src="http://maps.googl ...

The HTTP response object in Express does not provide any data in its return

While working on developing a server using express js, I encountered an issue. When I send a get request to my endpoint from another server, the response is received successfully; however, it does not contain the data that was sent by the server after res. ...

Send the user back to the homepage without the need to refresh the page

When the user clicks "Okay" in my window.prompt, the code below opens a new tab. Is there a way to direct the user to the home page without opening a new tab? if (window.confirm("Do you really want to leave?")) { window.open("./Tutoria ...

Create a compass application using React-Native

I am attempting to create a compass, but I am unsure how to utilize the Magnetometer data. Below is my Compass class: class Compass extends Component { constructor(props) { super(props); } componentWillMount(){ this._animeRotation = new Ani ...