Guide on converting a JavaScript object into an array consisting of key and value pairs

I have information that appears as follows:

[{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}]

My goal is to convert it into:

{"a":["apple", "alpha"], "b": ["ball"], "c":["cat"]}

Answer №1

If you're looking to achieve this, utilizing a reduce function is the way to go.

const items = [{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}]

const modified = items.reduce((accumulator, current) => {
  accumulator[current.letter] = accumulator[current.letter] || [];
  accumulator[current.letter].push(current.word);
  return accumulator;
}, {});

console.log(modified);

Answer №2

Is this the kind of thing you're looking for?

let list = [{"letter": "x", "word" : "xylophone"}, {"letter": "y", "word":"yellow"}, {"letter": "z", "word":"zebra"}, {"letter": "x", "word":"x-ray"}];

let result = {};
for (let item of list)
  (result[item.letter] = result[item.letter] || []).push(item.word);
  
console.log(result)

Answer №3

After analyzing the new data, here is the method I will use:

let items = [{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}]

let result = {}
items.forEach(function(item){
    let key = item['letter']
    let value = item['word']
    if(result[key]){
        result[key] = [...result[key], value];
    }else{
        result[key] = [value];
    }
})

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

Utilizing the nested combination of map and filter functions

Struggling to grasp the concept of functional programming in JavaScript, my aim is to extract object boxart items with width=150 and height=200. Console.log(arr) the output shows [ [ [ [Object] ], [ [Object] ] ], [ [ [Object] ], [ [Object] ] ] ] I&apos ...

Android textView is populated with randomly generated alphanumeric text after parsing file

I have a parse file coming from parse.com as a string message, and I need to display it in a textView. ParseFile file = message.getParseFile(ParseConstants.KEY_FILE); String filePath = file.getDataInBackground().toString(); if (messageTy ...

Using Vue.js's ref within a v-for iteration

When attempting to utilize components within a v-for loop and initialize the ref for future access to their methods from the parent component, I encountered an issue. Below is a simplified version of the code that demonstrates my scenario: <template> ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

Retrieve the information from the recently completed request

When the user inputs 'id' into the text field, I want to fetch a post based on the specific id entered by the user. If no id is provided, I would like to fetch the entire array of posts and then retrieve an id from the fetched data for testing pu ...

Example: Utilizing data transfer from model to directive

I have a question regarding a specific part in an example from Thinkster. I believe my confusion is due to my limited understanding of JavaScript and AngularJS fundamentals. I've been teaching myself since December, starting with the basics of JavaScr ...

Conceal the .dropdown-backdrop from bootstrap using solely CSS styling techniques

Is there a way to hide the .dropdown-backdrop element from Bootstrap for a specific dropdown on a webpage using only CSS? I found a solution that involves Javascript, you can view it on JSFiddle here. However, I am hoping to achieve this without relying o ...

Limit the character count in a textarea

My goal is to control the number of characters that can be entered into a textarea. While I am aware that I could simply use a substring to limit the characters, I prefer to visually inform the user when their text has reached the maximum length. The maxl ...

Searching for the precise error name being thrown in MySQL using Node.js

Currently, I am in the process of constructing a server using node.js (express) and mysql felix. The issue I am facing is that occasionally I encounter a duplicate error when running a certain query. I have exhausted all of my attempts to handle this err ...

The functionality of ng-switch appears to be malfunctioning

Take a look at this code snippet: <script src="angular.min.js"></script> <script src="jquery-1.6.4.js"></script> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller("myContr ...

Response received from the server

I am looking to display server response error messages within a form after submission. By using the following code in my JavaScript, I am able to retrieve the error message: .error(function (data, status, header, config) { $scope.postDataSuccessfully ...

Getting JSON data from an Angular JS controller can be achieved by utilizing the built-in

My user login function includes a method called logincheck, which takes in parameters and sends a request to the server. Upon success, it redirects the user to the dashboard with the member ID. this.logincheck = function(log) { var pa ...

Testing a component in Angular 2 that utilizes the router-outlet functionality

I recently set up an angular 2 project using angular-cli. As part of the setup, I created a separate AppRoutingModule that exports RouterModule and added it to the imports array in AppModule. Additionally, I have the appComponent which was generated by an ...

Slider handle for Material UI in React component reaches the range value

In my application, I am using a range slider component from material-UI. The main page displays a data table with the fields: id, name, current price, new price. The current price for each item is fixed, but the new price will be determined based on the s ...

Assign values to variables in a JavaScript file using node.js

My tech stack includes node.js, express.js, and either pug or jade. Within my server, I inject a variable called pageId into a view. In the pug view, I utilize this variable using the following script: script. document.addEventListener('DOMConten ...

Animated dropdown feature spanning the entire width of the screen

I successfully developed a basic dropdown menu with full-width sub-menu functionality. Check it out on jsFiddle: $(document).ready(function(){ $(".drop").hide(); $(".link-1").mouseenter(function(){ $('.link-1-drop').slide ...

Dealing with an empty request.FILES using FileUploadParser in Django Rest Framework and Angular file upload technique

Uploading files in an angular view can sometimes be tricky, especially when using templates. The code snippet below shows how to upload multiple and single files using Angular File Upload library. Multiple <input type="file" name="file" nv-file-select= ...

I am currently attempting to find a color picker element within a parent class using Cypress CSS Locator. While I am able to reach the parent element, I am unsure of the correct method to target the

My user interface has a list of elements displayed in 2 columns. The first column shows the name of the item, such as Manager, Operator, and the list is expected to grow. The second column consists of a color picker element where you can choose a color. I ...

What is a way to nest a promise request within another request?

Q: How can I create a new promise within a request, and then return it in a nested request? Here is the code snippet: request({ // --------------request 1------------ url: request_data.url, method: request_data.method, form: request_data.data ...

AngularJS: Transitioning from Expressions to Javascript (Coffeescript)

Looking to convert an expression into JavaScript in order to maintain an object's value in $scope: <dl class = "mortgage-information"> <dt><abbr title = "Loan-to-value Ratio">LTV</abbr></dt> <dd>{{(total_fi ...