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

Using jQuery to trigger a click event on a radio button prevents the button from being checked

Having trouble with using the .trigger("click"); function on radio buttons to activate a button in a form. When I use the code below, the button is triggered as expected. However, it seems to be interfering with the radio button, causing it to appear chec ...

Using JavaScript, reload the page once the data has been retrieved from an Excel spreadsheet

I'm facing an issue with my JavaScript code. Here's what I have: a = Excel.Workbooks.open("C:/work/ind12.xls").ActiveSheet.Cells.find("value"); if(a == null) document.getElementById('dateV ...

Preventing Div items from rearranging during size transitions using toggleClass

When I click on an element with the ID "id", I use toggleClass to resize a div from 10px to 500px in width. This is done partly to show/hide content. However, the issue arises when the transition occurs and the contents of the div start rearranging, overfl ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

Modify the classname of two element class i

I am trying to change the class on click within an <i> element that has 2 classes. The first class is always "fa" and the second class can be either "fa-minus" or "fa-plus". I need to toggle between "minus" and "plus" based on the current class. Ca ...

What is the best way to substitute </br> and <br/> with in a text?

Is there a way to replace </br> and <br/> with \n functionally? There seems to be varied responses to this query. Errors are often made when writing the break tag. The solutions for both types of breaks mentioned above are detailed below ...

Another option instead of preloading images

Currently, I am in the process of creating a jQuery slideshow. After reviewing numerous tutorials on the subject, it appears that most recommend preloading images using code similar to the following: imageArray[imageNum++] = new imageItem(imageDir + "02. ...

Elements on the page are quivering as a result of the CSS animation

When a user clicks anywhere on a div, I have added a ripple effect to give it some interaction. However, there is an issue where the element shakes and becomes blurry when the page is in full screen mode until the ripple effect disappears. Below is the Ja ...

Extracting arrays from JSON in Angular: A step-by-step guide

I am currently working with Angular2 (version 5) and facing an issue. I am able to make an HTTP request and receive JSON data. While I know how to access and use individual values, I am struggling with accessing and extracting the two arrays inside an elem ...

Issue with Moment.js incorrectly formatting date fields to a day prior to the expected date

Currently, I am attempting to resolve a small issue in my code related to a tiny bug. In my React component, I have set an initial state as follows: const initialFormData = Object.freeze({ date: Moment(new Date()).format('YYYY-MM-DD'), pr ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Enhancing Couchdb documents with unique id and author information through an update handler

Is there a way to include additional fields using the update handler in Couchdb? I'm trying to insert the author (with a validation function to verify that the user is logged in) and the id when creating a new document via an update handler. The auth ...

Converting SOAP to JSONX using XSLT with array complications

Currently, I am delving into the realm of XSLT and I find myself in need of assistance. Specifically, I am tasked with transforming a SOAP message into Jsonx format. The challenge lies in the "body" field where I need all children to be of type array, exce ...

How can I update a specific element within an array of objects in JavaScript based on its reference rather than its index position?

I am dealing with multiple arrays of objects x=[ {a:1}, {b:2}, {c:3}, {d:4} ] y=[ {e:5}, {f:6}, {g:7}, {h:8} ] (etc) and I have a list of references pointing to the objects I need to replace. Instead of having an index into the array, I hold reference ...

Display an image when the cursor hovers over a text

I'm attempting to display an image when hovering over specific text. The image should not replace the text, but appear in a different location. The concept is as follows: When hovering over the word "Google", the Google logo should appear in the red ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

Typing text into an input field by tapping on a picture

Is there a way to create a feature where users can browse and insert images, which will pull the image URL (all image information is stored in a database) into an input field for submission? Similar to how WordPress allows you to browse, select an image, ...

What is the best way to apply a CSS class to my anchor tag using JavaScript?

I have a good grasp of using JavaScript to insert an anchor element into my webpage. For instance, var userName_a = document.createElement('a'); However, I am interested in adding a style name to that same element as well. I attempted the follo ...

Can you explain how the interactive notification on stackoverflow is generated when you are responding to a question and someone posts a new answer?

Have you ever been in a situation where you're writing an answer to a question, but then someone else posts their response and a popup appears notifying you of the new answer? I'm curious about how that whole process works. It seems like the answ ...

Playing sound using jQuery when the body of the page is replaced

I am facing an issue with my website where I have implemented a jQuery full body refresh every 30 seconds. However, I want to add a short sound to play every time the page refreshes. Despite trying various methods, the sound works on my computer browsers ( ...