Creating a loop in Javascript that accesses values from a JSON file and uses the nested data within the loop as a separate JSON object

I am working with a list of user uuids stored in the myContactsUuids array. I am using the forEach() method to iterate through them and add each user, retrieved using the new ChatEngine.User(uuid) function, to the myContacts array.

myContactsUuids = ["john_doe_001", "john_doe_005"];
// initializing a global array of users
myContacts = {};

myContactsUuids.forEach(function(uuid) {

 myContacts[uuid] = new ChatEngine.User(uuid);

});

Now, I want to enhance this by adding additional data nested under each uuid. I aim to pass this as a JSON object with the user uuid as a string in the ChatEngine.User() function.

Here is an example of the user data structure:

myContactsUuids = {"john_doe_001":{"username":"John Doe","avatar_url":"http://someurl"},"john_doe_003":{"username":"Another John Doe","avatar_url":"http://someurl"}};

There is also a ChatEngine.User(uuid,data) function, which takes the user uuid string and data json object. So, for each user in the loop, it would look something like this:

new $scope.ChatEngine.User("john_doe_001", {"username":"John Doe","avatar_url":"http://someurl"});

I am unsure of the best way to write a loop for this scenario and pass the necessary data to it, and then add the retrieved users to the array as in the simple function. Possibly, using each() might help, but I am not sure of the correct approach.

The solution provided by @Ele seems to work, but I require the resulting array to be formatted like this:

{ "john_doe_001":{"uuid":"john_doe_001","data":{"username":"John Doe","avatar_url":"http://someurl"}},"john_doe_003":{"uuid":"john_doe_003","data":{"username":"Another John Doe","avatar_url":"http://someurl"}} }

Answer №1

Utilize the combination of Object.entries and map functions for your solution

var result = Object.entries(myContactsUuids)
                   .map(([uuid, data]) => ({ [uuid]: new $scope.ChatEngine.User(uuid, data) }));

Here’s an example to demonstrate the process:

var ChatEngine = {
    User: function(uuid, data) {
      this.uuid = uuid;
      this.data = data;
    }
}

var myContactsUuids = {"john_doe_001":{"username":"John Doe","avatar_url":"http://someurl"},"john_doe_003":{"username":"Another John Doe","avatar_url":"http://someurl"}};
var result = Object.entries(myContactsUuids)
                       .map(([uuid, data]) => ({ [uuid]: new ChatEngine.User(uuid, data) }));
                       
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Employ the reduce function to construct the desired output:

{
    "john_doe_1": {
        "data": {"2": 1}
        },
    "john_doe_2": {
        "data": {"a": 1}
    }
}

var ChatEngine = {
    User: function(uuid, data) {
      this.uuid = uuid;
      this.data = data;
    }
}

var myContactsUuids = {"john_doe_001":{"username":"John Doe","avatar_url":"http://someurl"},"john_doe_003":{"username":"Another John Doe","avatar_url":"http://someurl"}},
    result = Object.entries(myContactsUuids)
                   .reduce((a, [uuid, data]) => {
                      a[uuid] = new ChatEngine.User(uuid, data);
                      return a;
                   }, {});
                       
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 to send URL parameters to a different page with the help of express and Node.js

Hey there, I'm currently working on a chat app which you can check out here. I'm in the process of enabling users to join specific rooms by typing in a URL like , assuming they are logged in. I manage user login and signup with passwords. Here&ap ...

What is the method for accessing the Redux store content directly in the console, without using any developer tools

By utilizing React Devtools, I am able to access the store by: $r.store.getState() Is there an alternate method to retrieve the store without using React Devtools? ...

jQuery MaskMoney - position input at the start of the field

Check out this jsfiddle I created to showcase the issue I'm facing. Whenever I click on the input field, the cursor automatically goes to the end. This means that I have to start typing cents before dollars, which is not the behavior I want. My desire ...

Iterate through each element in the array and manipulate the corresponding data

I am trying to figure out a way to assign a unique id to each item in an array and send it to the "script.js" file for individual data processing. <script href="script.js"></sciprt> script.js: $(function(){ $('#box' ...

How can I convert an xlsx file to JSON using ExcelJS in Node.js?

https://github.com/guyonroche/exceljs I am a beginner with exceljs and just came across the description of exceljs on github. The description states: "Read, manipulate and write spreadsheet data and styles to XLSX and JSON." I am looking for a way to ...

Navigate to the final element of a mapped array

My current project includes a Message component that showcases all messages, whether incoming or outgoing, within a single thread. One feature I am aiming to implement involves ensuring that the most recent message, a freshly typed one, or an incoming mes ...

Obtaining a state hook value within an imported function in React

In order to access a value from the state hook stored in a special function, it is straightforward to do so in a functional component. For example, this can be achieved in App.js like this: import React from 'react'; import { Switch, Route, with ...

Exiting or returning from a $scope function in AngularJS: a guide

There are times when I need to exit from my $scope function based on a certain condition. I have attempted to achieve this using the return statement. However, my efforts have been in vain as it only exits from the current loop and not from the main scop ...

Disabling modal popup buttons in Bootstrap 4 using Javascript

JSFiddle DEMO: https://jsfiddle.net/2yx16k8L/ I'm encountering an issue with my JS code. I want a click on a div to open the entire content within it. However, this action is causing the modal button in the dropdown to stop working. How can I resolve ...

When material skinning is enabled, the skinned animation mesh in Three.js mysteriously vanishes

After exporting an animated model from Blender, I encountered an issue with instantiating it in my project. Although I was able to create the THREE.Animation and model, I found that the animation was not working. I soon discovered that I needed to set skin ...

How can I ensure that my script reruns when the window is resized?

Clearly, the question is quite straightforward... I have a script that is drawing graphics across the window. Currently, when I resize the window (e.g., make it full screen), the script only responds to the original size of the window. It should refresh a ...

When using the RxJs Pipe with MAP in Angular and Ionic, it may not return a value in windows, but it works perfectly in Mac when used with HttpClient

I'm currently using RxJs Pipe with Map for a network request in my Angular/Ionic project. Interestingly, while I do receive a successful response in the network log, the MAP function fails to return any value. Notable Observations Strangely, this fu ...

Obtaining a Byte[] from an IntPtr in C#

I am dealing with a .dll file (not created by me) that contains a delegate. The Callback function for this delegate is defined as: "CallBackFN(ushort opCOde, IntPtr payload, uint size, uint localIP)" My question is how can I convert IntPtr to Byte[]? I ...

Exploring the process of obtaining JSON data in an ASP.NET web API

We have an external company that is sending JSON data to one of our servers, and I need to create a POST API to receive this data. Here is the current implementation: [System.Web.Http.HttpPost] [System.Web.Http.ActionName("sensor")] public void PushSensor ...

Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the web ...

Ways to showcase a list in 3 columns on larger screens and 1 column on smaller screens

When viewing on a computer, my list appears like this: https://i.sstatic.net/fNhaP.png However, when I switch to a phone, only the first column is visible and the list does not continue in a single column format. I am utilizing Bootstrap for my layout, a ...

Modifying content on the fly with a dropdownlist in Knockout framework

Currently experimenting with implementing inline editing through knockout. I stumbled upon this informative thread about Knockout Inline Edit Binding After some tweaks to introduce a "Select" for edit mode, the functionality seems to be working fine. Howe ...

A numerical input field that removes non-numeric characters without removing existing numbers?

Currently, I have implemented the following code: <input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')"> This code restricts users from entering anything other than numbers into a field on my webpage. However, I hav ...

Discovering the Week by week commencement and conclusion dates utilizing angularjs

Previously, I was utilizing the angularjs-DatePicker from npm. With this plugin, I could easily select a date from the calendar. However, now I require two fields - FromDate and ToDate - to display the week StartDate and EndDate whenever a date within that ...

Using Three.js and WebGL to create transparent layers that conceal the planes positioned behind them

Have you ever noticed that in Three.js / WebGL, when you have two planes and one or both are transparent, the plane behind can be hidden by the transparent plane on top? Why does this happen? ...