I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this

myArray = [
    {
      id: 3,
      data: foo
    },
    {
      id: 7,
      data: bar
    }
]

However, I would like to transform it into the following structure

 transformedArray = {
    3: {
        id: 3,
        data: foo
    },
    7: {
        data: bar
    }
}

The presence of 'id' in each sub-object is not crucial but could be helpful. Is there a straightforward method to convert a property into an index?

Any assistance on this matter would be greatly appreciated!

Answer №1

newObj = {};
originalObj.forEach(function(item){
    newObj[item.id] = item;
});

Answer №2

When it comes to manipulating objects, it's always a good idea to leverage the power of the Underscore JavaScript library. This library simplifies working with objects and takes care of any browser compatibility issues for you. In this case, I recommend using the map function:

var updatedObj = _.map(obj, function (subobj) {
  var tempObj = {};
  tempObj[subobj.id] = subobj;
  return tempObj;
});

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

Determine if the input number exceeds a specified threshold by implementing JavaScript

My attempt at performing calculations on a page is not yielding the desired results. I have tinkered with the code below, but it doesn't seem to be working as expected. Can anyone provide guidance on where I might be going wrong? Specifically, I want ...

Preserving the order of XML elements in Perl when converting to JSON: Best practices

My task involves dealing with a configuration file in XML format that needs to be converted to JSON while maintaining the order of elements. I have been using the XML2JSON module in perl for this purpose, but it is not preserving the sequence of XML elemen ...

What is the best way to assign specific JSON data "values" to named $scope variables in Angular when retrieving data from a SPARQL query?

As a newcomer to Angular, I apologize if my question seems ignorant. I have searched through dataversity, stack overflow, google ... as well as w3c and tried various "try it and see solutions," but I just can't seem to make this work. Essentially, I ...

Submit form using jQuery after making an AJAX request with jQuery's $

I'm working on the following code: $.get(link, function(data, status) { document.getElementById("test").value = data; }); $('#formtest').submit(); Everything works fine in Firefox, but in Google Chrome the submit is done before t ...

Troubleshooting: Issue with Displaying $Http JSON Response in AngularJS View

Struggling to retrieve JSON data from an API and display it in a view using AngularJS. Although I am able to fetch the data correctly, I am facing difficulties in showing it in the view. Whenever I try to access the object's data, I constantly receive ...

Testing of onClick event in a React component using styled-components with Sinon spies

Utilizing sinon to test a react component and verify that an onClick function is triggered. Struggling to target the element to click on due to the use of styled-components. Encountering this error message: The "simulate" method should only be run on ...

Using JavaScript/jQuery to tally characters

Here is the code snippet that I am currently working with: PHP <input style="color:red;font-size:12pt;font-style:italic;" readonly="" type="text" name="q22length" size="3" maxlength="3" value="50"/> <textarea onkeydown="textCounter(doc ...

Discover the power of Material UI combined with React Router to create dynamic BreadCrumbs with unique

I am facing a challenge while trying to incorporate material-ui breadcrumbs with reactRouter. The issue arises because the script is unable to find the correct string for ':id' in the breadcrumbs when it is not specified. (It works as intended wh ...

Utilizing the array result obtained from the fetch function

Seeking assistance with a coding issue. I am puzzled as to why I am unable to utilize the data returned from an API call outside of its function, even though there are no errors occurring. The fetchUser function successfully retrieves the data from the API ...

Is it possible for third party packages to function properly without the node_modules directory?

Whenever we push our code to GitHub or any other remote repository service, we make sure to exclude the node_modules folder. This begs the question: how are all the third-party libraries functioning on the hosted website if the node_modules folder is not ...

Retrieving information from MongoDB for a specific ObjectID associated with the current authenticated user

Having two collections in my MongoDB structured as follows: Data User: id: ObjectId ("5fb39e3d11eaad3e30cfb1b0") userName: "Tobias" password: "yyy" id: ObjectId ("5fb3c83fb774ff3340482250") userName: "Thor&qu ...

Navigating PopUpWindows using SeleniumIn this guide, learn the best

I have attempted to manage a particular PopUp / new Window in Java using SeleniumServer, but unfortunately, it is not functioning as expected. Here is what I have tried: selenium.click("css=a[title=\"Some irrelevant title\"] > div.text"); Thr ...

Guide to creating a dynamic form using Phonegap and jQuery Mobile

Currently, I am working on an iPhone and Android app using Phonegap and jQueryMobile. The app receives a JSON with a form that was generated by my ruby on rails web application. However, I have encountered a significant issue. The form is quite large, con ...

Encountering this issue: Unable to access the property 'length' of an undefined variable

I'm currently developing an app using nuxt, vuetify 2, and typescript. Within the app, I have radio buttons (referred to as b1 and b2) and text fields (referred to as t1, t2, t3). When a user clicks on b1, it displays t1 and t3. On the other hand, w ...

Having trouble retrieving input field values with Angular.js

I am struggling to access the input field values in my Angular.js application. Below is the code snippet I am using: <div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon ndrftextwidth text-right" style="width:180px"& ...

Applying onclick css changes to a specific duplicate div among several others?

Recently, I encountered a situation where I have multiple identical divs on a page. <div class="class" ng-click="example()"></div> With the use of Angular 1.6.4 and jQuery, these divs are styled with background color and border color. Now, w ...

Automatically Populate Text Field with the URL of the Current Page

I am hoping to automatically fill a hidden text field with the URL of the current page so that I can keep track of where form submissions are coming from. This simple solution will help me streamline my inquiry responses and save time. To clarify, upon lo ...

unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded: [Object, Object, Object, Obj ...

"Implementing a method to convert a varbinary array returned in JSON to an image and displaying it on an ImageView in an

need assistance in converting a varbinary array returned by a web service to an image and displaying it on an imageview. any help would be greatly appreciated. thank you. ...

The JSON API encountered an error when trying to send a PDF file, specifically a TypeError stating that an object of type bytes cannot

Is there a way to successfully send a pdf file using the SendPulse API? I am able to send txt files, but encountering issues with sending pdf files. import base64 def fn(): value = None with open('/tmp/test.pdf', 'r ...