Creating a dynamic map in AngularJS by parsing and utilizing data from a JSON file

Looking to create a map from JSON data returned by a RESTFUL WEB Service using AngularJS.

Here is an example of the JSON format:

myJSON = [{
    id: 8,
    color: "red",
    value: "#f00"
},
{
    id: 37,
    color: "green",
    value: "#0f0"
},
{
    id: 45,
    color: "blue",
    value: "#00f"
}]

The goal is to build a map using id & value from the JSON provided. An initial idea might look like this:

var map = [myJSON.id : myJSON.value]

This would result in a map like:

map = {8: "red", 37: "green", 45: "blue"}

While a simple solution involves looping through the JSON array to construct the map, are there alternative methods to achieve this goal?

Answer №1

Utilize the reduce method on an array to achieve the desired outcome. For more information, visit the documentation on MDN. It's important to clarify that this approach does not involve Angular but rather plain JavaScript.

var mappedData = myJSON.reduce(function(mapping, item) {
    mapping[item.id] = item.color;
    return mapping;
}, {});

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

How can I replace the unsightly "Web page not available" error in WebView on Android with a more visually pleasing alternative?

In my WebView Activity, I sometimes encounter issues with loading properly when the WIFI/DATA connection is poor or disconnected. This could potentially be a common occurrence once my app is in use. I'm curious to know how I can replace the unattracti ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

One approach to returning multiple objects based on a column with multiple values in Dynamic Linq

Situation: I am facing a task where I need to export an excel file containing a list of Parts. Users have the ability to select specific columns and only retrieve data from those selected columns in the exported file. To handle this dynamic report, I have ...

Using a Material-UI component to activate a React Router Link

Currently, I am facing an issue while using material-ui components in react with react-router. The problem arises when I try to display list-items that double up as link elements but also have a submenu inside which should not activate the parent link. Unf ...

Using jQuery to arrange information from an API into a table

Currently, I am in the process of learning jQuery as it is a new concept for me. I have attempted to make a request to an example API and received an array of objects that need to be listed in a table. However, I am facing difficulty in sorting it within t ...

myObject loop not functioning properly in Internet Explorer version 10

Could someone please point out what is wrong with this code snippet? HTML: <div id="res"></div> Javascript: var myObject = { "a" : { src : "someimagepath_a.png" }, "b" : { src : "someimagepath_b.png" }, }; va ...

Building a Modal in React and Triggering it for Display, followed by Making an AJAX Request upon Submission

Check out my CodePen snippet (minus delete ajax request): http://codepen.io/martincarlin87/pen/KzPWOw I've been diving into the world of React recently, and I'm working on converting a page in my web application to utilize React instead of just ...

Tips on extracting a specific value from an httpClient response in Razorpages

return await request.Content.ReadAsStringAsync(); I am using this code to get a response from an API, but I only need a specific object. How can I filter the response to get just that object? using (var _client = new HttpClient()) { try { ...

Encountering an error in AngularJS $http calls while trying to loop: TypeError - object is not functioning

Currently, I am in the process of automating the population of my app's database with Dummy Data to eliminate the manual task of adding users, friends, and more. To achieve this, I have implemented nested AngularJS $http requests that interact with my ...

Preserving scroll position when updating a partial page template using Rails and AJAX

When I am utilizing long polling, I encounter an issue where every time I use AJAX to refresh a page partial inside a scrollable div, the contents automatically scroll to the top. Is there any way to load the partial while maintaining the current scroll ...

How can you fetch data from a PHP file using AJAX before performing a header redirect?

I am currently in the process of adding more dynamism to my website. I have developed a forum from scratch and now I am integrating JavaScript into it. All the PHP backend work is complete. My next goal is to enable user login without having to refresh the ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

Converting Python dictionary to NodeJS dictionary: A step-by-step guide

In my possession is a dictionary that goes as follows: my_dict = {"A":"a", "B":"b", "C":"c"} If I choose to store it utilizing json, the process would be like this: with open('my_dict.json', 'w') as fp: json.dump(my_dict , fp, in ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

Calling functions in AngularJS/HTML can help you execute specific

Just started with angularjs and facing some major issues haha... I have something that seems to be working fine, but I can't figure out what's wrong with this code... can someone please help me? Here it is: Basically, the scope.create function ...

Fullcalendar JS will easily identify dates with events, allowing users to simply click on those dates to redirect to a specific URL

When looking at the official example, we can see that the events are displayed in a typical calendar format: https://fullcalendar.io/js/fullcalendar-3.5.0/demos/basic-views.html Each event is listed in the calendar, and clicking on an individual event wi ...

Experiencing difficulty with an Ajax jQuery JSON script

My current script is designed to send form values to a network script in order to receive a json object: $(document).ready(function () { $("#sitesearch").click(function (event) { var url = 'http://192.168.1.75/search/index.php' ...

Currently dealing with a script that utilizes AJAX GET to incorporate JSON data into my table

Greetings and thank you for taking the time to read this! Within my HTML, I have implemented a form element that allows inputting data into 5 different fields. This data is then transmitted to a database using my unique API key. Once stored in the database ...

Another option instead of using ng-repeat when scope is not required

Currently, I am facing a problem where Angular is generating a large number of rows and columns, resulting in poor performance! I suspect that the issue lies with ng-repeat creating a new scope for each element it generates. However, since my function doe ...

Converting HTML to JSON using jQuery

Currently, I am utilizing the jQuery template plugin to dynamically create HTML based on JSON data that user can then modify (and even change). My goal is to find a way to convert this HTML back into JSON format so that it can be saved back to my server. ...