Transform an array into an object utilizing only underscore

I'm currently learning about underscore and came across a task that I could use some assistance with. I have an array containing objects like the following:

[
    // ...
    {
            "type": "presence",
            "params": {
                "interval": 15,
                "foo": "something",
                "link": {
                    "fp_type": "1",
                    "fp_ext_id": "2"
            },
    },
    {
            "type": "bar",
            "params": {
                "interval": 30,
                "foo": "foo",
                "link": {
                    "fp_type": "2",
                    "fp_ext_id": "3"
                },
            },
    },
    // ...
]

The task at hand requires using underscore to convert these array items into an object where the key is the item's type and the value is its parameters, as shown below:

{
  // ...
  "presence": {
    "interval": 15,
    "foo": "something",
    "link": {
        "fp_type": "1",
        "fp_ext_id": "2"
     },
  }, 
  "bar": {
       "interval": 30,
       "foo": "foo",
       "link": {
           "fp_type": "2",
           "fp_ext_id": "3"
       },
  // ...
}

Answer №1

Here is a way to accomplish the task:

var x = [    
    {
            "type": "presence",
            "params": {
                "interval": 15,
                "foo": "something",
                "link": {
                    "fp_type": "sponsor",
                    "fp_ext_id": "spotme"
                },
            },
    },
    {
            "type": "bar",
            "params": {
                "interval": 30,
                "foo": "foo",
                "link": {
                    "fp_type": "2",
                    "fp_ext_id": "3"
                },
            },
    }
];

var y = _.map(x, function(i) {
  let obj = {};
  obj[i.type] = i.params;
  return obj;
});
//console.log(y);

var result = y.reduce(function(obj,item) {
  obj[_.keys(item)[0]] = _.values(item)[0]; 
  return obj;
}, {});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Check out the DEMO here

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

Struggling to fetch data from the Strapi page is posing a challenge

Currently, I am facing an issue where the frontend developers on my team are unable to retrieve data from the backend that I built for them using Strapi. Even after pulling my changes from github, they continue to face difficulties accessing the data. The ...

Updating a hyperlink with data dynamically upon clicking a different button using jQuery

I need to create a script that will add the id of 'peter' to the hyperlink of anchor 'jack' when 'peter' is clicked. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery. ...

JavaScript problem with hovering action causing additional buttons to appear

Currently, I am developing a user interface where, upon hovering over an LI element, 2 buttons appear to provide additional functionality - "edit" and "remove". However, I am facing challenges with the mouse hit zones. The mouseover function works effect ...

A technique, such as regular expressions, can be used to detect the quantity of newline characters in the text entered by the user in a text area

I'm trying to figure out how to count the number of newline characters (or whatever is inserted when the user presses the return key) in a textarea's value. I believe I should be using a regular expression for this task, but I'm not very ski ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

What could be causing the return of undefined upon execution?

function updateTitle(title) { title = "updated title"; } var currentTitle = "original title"; currentTitle = updateTitle(currentTitle); console.log(currentTitle) I'm just starting to learn JavaScript and I'm curious about why this code behav ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Struggling with UI-Grid's single filter feature when dealing with intricate data structures?

I'm currently working with UI-Grid and facing a challenge while applying a filter to some complex data using their single filter example. Initially, everything runs smoothly when I use simple selectors. However, as soon as I attempt to delve one level ...

Customizing Marker Images in Google Maps JavaScript API

Currently, I am using a workaround to rotate a custom image marker in Google Maps. The issue I am encountering is regarding sizing. For example, if my PNG image is 400px wide and 200px high. When rotating the image so the width becomes vertical, it gets ...

The animation in Rive feels sluggish when navigating to a page with animation in Blazor WASM, despite implementing dispose methods

After attempting to display river animation on the index page using Blazor WASM (basic template), I encountered some performance issues. When navigating back and forth between the Counter page and the index page, I noticed that after around 20 clicks, the ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Combine loop results into a string using jQuery

When using jQuery, I need to append a multiline string to an element by adding a string return from each value in a for loop. $("songs-table-tr").append('tr id="songs-table-tr'+count+'" style="display: none">\ ...

What is the best way to direct users to the individual product page once they make a selection

On my main products page, I am fetching all the products from a local JSON file. interface productItem { id: number; name: string; image: string; price?: string; prices: { half: string; full: string; }; ...

Is it possible to modify the inactive color of just one radio button in Framework7?

Is there a way to change the inactive color of only one radio button in Framework7? I am aware that using the CSS variable --f7-radio-inactive-color allows me to set the inactive color for all radio buttons. However, I specifically want to modify the inac ...

Expansive image coverage

My footer design includes a rounded left image, a repeating middle section, and a rounded right image. How can I ensure that it scales perfectly responsively without overlapping? Ideally, the solution would involve adjusting the width of the middle section ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

Connect Promise.all() with an array of identification numbers

I'm fairly new to working with Promises and I have a question regarding linking the results of `Promises.all()` to unique IDs for each promise once they resolve. Currently, I am making requests to a remote server and retrieving data for each request. ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Strange issue with Firefox when utilizing disabled attribute as "disabled"

I found a curious bug in Firefox: Check out (unfortunately not reproducible in jsfiddle) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> < ...