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

Outputting undefined values when processing an http post array

I seem to have encountered a major issue. Despite my efforts, I am seeing an undefined value when trying to display this JSON data. {"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [ {"sensor_serial":"SensorSerial1", "id":"11E807676E3F3 ...

The prop observation was activated without any alterations

Within my component, I have a prop X that I assign to data Y during the created hook. This setup allows me to easily modify Y without affecting X. Both X and Y are Arrays. Additionally, I've set up a watch on prop X to ensure Y is updated whenever X ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

I am unable to load any HTML files in my VueJS iframe, except for the index.html located in the public

Within the template of my vue component, I am utilizing the following code: <iframe width="1000vw" height="600vh" src="../../public/myHtmlFile.html"></iframe> Unfortunately, the file specified in the src attribut ...

Creating a dynamic JSON object with repeated keys: A step-by-step guide

My current predicament seems quite challenging as my supervisor has mandated that I send a JSON over an AJAX post call using jQuery with duplicate keys. Struggling to achieve this task, I found that if I were to structure the JSON like so: $.post("someurl ...

Utilizing Next.js for dynamic routing with [[...slug.js]] allows for comprehensive URL handling and seamless 404 page display for links leading back to the homepage - a feature

In order to achieve a single dynamic route for handling all requests in this application, I have created a file called [[...slug]].js. Data loading is managed using getServerSideProps(), allowing for server-side rendering. Notably, there are no index.js fi ...

The script is stuck displaying the existing records, failing to update with any new ones

Kindly refrain from offering jQuery advice. This script is created to display additional database records when you scroll down to the bottom inside a div named results-container. The issue I'm encountering is that the same data keeps appearing. I&ap ...

What steps can I take to address security issues related to iframes?

Are there other security risks to consider when using iframes besides XSS vulnerabilities? How can I ensure that my website is secure when utilizing iframes? I've seen some JavaScript code that uses top.window, but I'm hesitant to rely on client ...

Is there a way to search for specific JSON elements using Retrofit?

Currently, I am utilizing Retrofit to fetch and parse JSON data that I have created and uploaded online. Even though I can successfully showcase all the data, as a newcomer to Retrofit, I find it challenging to grasp how to query and display specific items ...

Connecting two tables in an express API

Currently, I am in the process of developing an API using Express.js. At this stage, my initial tests are functioning correctly. My goal now is to retrieve values from two separate tables. For example, consider the following 2 tables: Table_A Id: 1, Name: ...

Load different tab contents in a view pager without having to fetch them again

I am using a view pager within a tabLayout to display content sourced from JSON data. Each page on the view pager contains different content, and I'm trying to figure out how to extract each page's content just once. Is there a method to achieve ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Guide for implementing async/await in conjunction with the eval() function within JavaScript

I'm currently using the eval function to evaluate strings and adding await to it to ensure all values are obtained, but unfortunately the await is not functioning correctly. Here is a snippet of my code: if (matchCard.card.status != "notstarted& ...

Tips for building a dynamic navigation menu using AngularJS

Looking to dynamically generate a navigation menu using an angularjs controller: index.html: <body> <div ng-controller="navi"> <ul> <li ng-repeat="nav in navigations"> <a href="{{nav.path ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

Can I simultaneously utilize submit and ajax functions?

As I work on CRUD for our website, the approach we are taking involves using submit. However, there are occasions where I need to pass data from a JS file to my controller (I am using Codeigniter). I am now considering whether it is common practice to do ...

Vue 3 list fails to refresh

Using an API, we are retrieving data: <script setup> import { onMounted, inject } from 'vue' let list = []; function initializeData() { axios .post("/some-link/here") .then((response) => { list ...

Ways to retrieve the returned value from the JS FETCH API outside of its scope

As a beginner in Typescript React and the Ionic framework, I am trying to use the JS FETCH API to fetch data from a third-party source. However, I am struggling to access this fetched data outside of the fetch function. If anyone could provide some guidan ...

Exporting modules for testing within a route or controller function

I'm relatively new to NodeJS and the concept of unit testing. Currently, I am using Jest, although the issue seems to persist with Mocha, Ava, or any other test framework. It appears that my problem revolves around the usage of export/import. In one ...

Creating a List with Sublists that are displayed when hovering over the parent List is a key element of effective design

Hovering over 'View Rows' should open up both New Records and Old Records <div> <li>Add Rows</li> <li>DeleteRows</li> <li>View Rows <ul> <li>View New Records</li ...