Operating on Javascript Objects with Randomized Keys

Once I retrieve my data from firebase, the result is an object containing multiple child objects.

myObj = 
{
    "J251525" : {
        "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c3823212c212d2520422f2321">[email protected]</a>",
        "description" : "CLEAN THE HOUSE",
        "refNumber" : "J251525"
    },
    "J512912" : {
        "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0248434f4751424f434b4e2c414d4f">[email protected]</a>",
        "description " : "BRUSH HORSE",
        "refNumber" : "J512912"
    },
    "J53f512" : {
        "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6fef7e4e4eff6fbf7fffa98f5f9fb">[email protected]</a>",
        "description " : "WASH CAR",
        "refNumber" : "J53f512"
    }
};

I aim to break down this data in order to present it using a layout similar to the one shown below in the thead/tbody of an html table.

https://i.sstatic.net/qpKBL.png

In order to achieve this, I need to:

  1. Create an array ['email', 'description', 'refNumber'] based on myObj data.
  2. Iterate through the object (Can we loop through an object?) and generate separate arrays like

['[email protected]', 'CLEAN THE HOUSE', 'J251525']

['[email protected]', 'BRUSH HORSE', 'J512912']

['[email protected]', 'WASH CAR', 'J53f512']

Starting this process is a bit challenging for me since typically when working with objects, I already know the keys without needing to iterate. In this case, I must determine how many objects are within the main object somehow. Furthermore, I cannot access data using myObj['J251525'] as I am unaware of the key J251525.

Please note that I am utilizing Typescript alongside Angular 2.

Answer №1

If you need to transform the object into a different format, you can achieve this by utilizing the following code snippet:

var myObj = 
{
    "J251525" : {
        "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="297d66646964686065076a6664">[email protected]</a>",
        "description" : "CLEAN THE HOUSE",
        "refNumber" : "J251525"
    },
    "J512912" : {
        "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c288838f8791828f838b8eec818d8f">[email protected]</a>",
        "description" : "BRUSH HORSE",
        "refNumber" : "J512912"
    },
    "J53f512" : {
        "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87cfc6d5d5dec7cac6cecba9c4c8ca">[email protected]</a>",
        "description" : "WASH CAR",
        "refNumber" : "J53f512"
    }
};

var result = Object.keys(myObj).map(function(key) {
  return [myObj[key].email, myObj[key].description, key];
});

console.log(result);

Answer №2

To efficiently extract and store object values in arrays nested within another array, you have the option to utilize the for..of loop or the Object.entries() method.

myObj = {
  "J251525": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4713080a070a060e0b6904080a">[email protected]</a>",
    "description": "CLEAN THE HOUSE",
    "refNumber": "J251525"
  },
  "J512912": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abe1eae6eef8ebe6eae2e785e8e4e6">[email protected]</a>",
    "description ": "BRUSH HORSE",
    "refNumber": "J512912"
  },
  "J53f512": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d555c4f4f445d505c5451335e5250">[email protected]</a>",
    "description ": "WASH CAR",
    "refNumber": "J53f512"
  }
};

let arr = [];

for (let [, obj] of Object.entries(myObj)) {
  arr.push([]);
  for (let [, value] of Object.entries(obj)) {
    arr[arr.length - 1].push(value);
  }
};

console.log(arr)


An alternative approach is to use Array.prototype.map() instead of a for..of loop for achieving the same outcome:

Object.entries(myObj).map(([,obj]) => Object.entries(obj).map(([,value]) => value))

Answer №3

Give this a shot:

for(let property in myObj) {
        let value = myObj[property];
        // Do something with the object here
        console.log(value.email);
        console.log(value.description);
        console.log(value.refNumber);
    }

Avoid creating a new object unnecessarily, as it will result in redundant operations. In a regular JavaScript array, you will have a similar structure with ordered integers (1, 2, 3, etc.) instead of random keys unless specific keys are required.

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

Best Practices for Implementing AngularJS Dependency Injection

I am excited to share that I have recently started delving into my very first Angular JS project. As I navigate through this new experience, I want to ensure that I am effectively managing Multiple dependency injection. Any insights, recommendations, or ...

Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray. An example of my HTML form: <form action="" method="post" name="myForm"> ID: <input type="text" name="id" /><br/> State (XX): <input type="text" name="state" /><br/> <p ...

Cypress - Mastering negative lookaheads in Regular Expressions

While experimenting with Cypress, I encountered an issue regarding a filter test. The goal is to verify that once the filter is removed, the search results should display values that were filtered out earlier. My attempt to achieve this scenario involves ...

Having Difficulty with Mathematical Operators in AngularJS

Here is the code snippet I am currently working with: $scope.calculateTotal = function() { $scope.totalAmounts = []; var total = 0; for (var i = 0; i < $scope.orderDetails.length; i++) { console.log($scope.orderDetails[i]['pric ...

Developing a unified input element containing numerous fields

After @grateful answered this question, I wanted to elaborate in case it could benefit others... In my project, there's a page called rsetup.php which has some PHP code to access a MySQL database for filling the HTML content of the page. This HTML ge ...

Step-by-step guide to initializing a project using React with Typescript and a functional server-side script

I am working on a project that involves a React Typescript app (created using Create React App). In this project, I need to have an executable script that can run alongside the React app. Both the app and the script are intended to only run on local machin ...

Plugin for saving inline edits in CKEditor 4

After creating a plugin for ajax save, I found the documentation confusing when it comes to implementation. How can I make the button responsive and able to save content using AJAX with PHP? Currently, I am unable to retrieve the content. Directory: /plug ...

Determine the output by applying a constant value to the input

I'm having an issue with a loop function. The goal of the code is to allow users to enter a quantity of goods they want to buy, and then JavaScript calculates a fixed value based on the chosen quantity, which should be printed out. This functionality ...

Adjusting the background hue of the 'td' element within an ajax request

When I press a button, an ajax call is triggered below. In this call, I append 'td' elements with values to a table. Specifically, on the line ''</td><td>' + result[i].preRiskCategory +', I am attempting to change ...

The troubleshooting of debugging javascript remotely on IntelliJ with the JetBrains Chrome extension is proving to be unsuccessful

I've been attempting to set up a debugger for some JavaScript files that I'm working on in IntelliJ (version 2020.1.4). Following the guidelines provided here Debug with JetBrains Chrome extension, I believe I have successfully completed all the ...

The color syntax in the text editor of Visual Studio 2022 is being lost when casting an interface

After attempting to cast an interface, the entire code turns white. let object : someInterface = <someInterface> someUnknownHapiRequestPayload View a screenshot of the text editor here I have already tried common troubleshooting steps such as updat ...

When PHP is connected to the database, Ajax remains inactive and does not perform any tasks

I am currently working on setting up a simple connection between JavaScript and my database using ajax and PHP. The goal is for JavaScript to receive a name from an HTML form, make changes to it, send it to PHP to check if the name already exists in the da ...

contrasting module export approaches

Let me clarify that my query does not revolve around the disparity between module.exports and exports. Instead, I am interested in understanding the contrast between exporting a function that generates an object containing the functions to be shared upon i ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

The issue with the value of the textarea in Selenium automated tests using

I have a webpage with Javascript where I've implemented a textarea using the following code: var textarea = $("<textarea>"); textarea.change(() => { console.log(textarea.val()); }); When I update the value in the textarea and then chang ...

"Trying to create a new project with 'ng new xxx' command resulted in error code -4048

Whenever I execute 'ng new projectName' in vs code, I encounter the following issue. ng new VirtualScroll ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com ] CREATE Vir ...

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...

Material UI - Radio buttons do not properly reflect the current state of the value

I'm diving into the world of full stack development and I'm working on a project to enhance my understanding of frontend programming with React JS and Material UI. Specifically, I've created a Dialog component to send data to the backend, bu ...

What is the process for configuring the injector in my application?

https://code.angularjs.org/1.0.0rc9/angular-1.0.0rc9.js I am facing an issue with the above link as it defines an external js file that I am not familiar with the injector to angular-1.0.0rc9.js. Due to this, my app is not running in the browser. Here is ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...