Converting Rails data into JSON objects using hashing techniques

I'm currently working on a Rails query that looks like this:

@c = RealEstateAgentAssignmentStatus.joins(:real_estate_agent_assignments =>:loan_application)
    .group("real_estate_agent_assignment_statuses.assignment_status").select("real_estate_agent_assignment_statuses.assignment_status,count(real_estate_assignments.loan_application_id)")
    .where("real_estate_agent_assignments.real_estate_agent_id = 188").count

After executing the query, I receive the Rails result in JSON format as follows:

var data = {
"Rejected By Customer/Bank":1, "Failed Screening":2, "Submitted":2, "Processing Stage":3 }

The reason for the JSON format is because I need to pass it to AngularJS for further processing.

Currently, I can only access the data like this:

data["Submitted"]

Is there a way to hash the result in Rails or convert it into an array so that I can access it like this:

data.status , data.value 

I considered mapping it in Rails, but I encountered an error. Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

Using Ruby:

array = data.map do |key, val|
    {
        type: key,
        amount: val
    }
end

Using JavaScript:

let array = [];
Object.entries(data).forEach(([key, val]) => {
    this.push({ type: key, amount: val }) 
}, array);

Answer №2

Rails Framework

To efficiently handle data in Ruby, you can utilize the OpenStruct class.

require 'ostruct'
data = {"status" => 'Rejected By Customer/Bank', "value" => 1}
os = OpenStruct.new data
os.status # Rejected By Customer/Bank
os.value # 1

Another approach is to define a custom method_missing in the Hash class, although it may not be recommended.

def method_missing(m)
  key = m.to_s
  return self[key] if self.has_key? key
  super
end

In both scenarios, your hash should contain keys like status and value. To transform your hash:

new_hash = h.map{ |key, value| OpenStruct.new({status: key, value: value }) }

Alternatively, without using OpenStruct:

new_hash = h.map{ |key, value| {status: key, value: value } }

After this conversion, you can access the data using:

new_hash[i].status
new_hash[i].value

JavaScript

For handling data in JavaScript, convert your hash into an array of objects. With AngularJS:

var data = [];
angular.forEach(your_json, function(k,v){ 
  this.push({ status: k, value: v }) 
}, data); 

I hope this explanation clarifies the process for you and proves to be beneficial.

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

Vue: Choosing an option during the execution of setInterval

I'm facing an issue where I can't select an option while a setInterval function is running on the page. The main problem is that an option cannot be selected at the same time as the setInterval timer fires. let updateDelay = 100; var vueObj = ...

Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div? I have put together a DEMO on codepen.io In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of ...

Counting radio buttons in AngularJS and handling undefined values when passing parameters

After spending countless hours trying to figure out how to count radio buttons, I encountered another issue where the value passed to ng-change would become "undefined". My question is, how can I successfully pass that value? Any assistance with counting o ...

A guide on accessing the first element in an array when performing multiplication within the Interval component in React.js

I am having trouble initiating an if statement from number 0 once the window is loaded, as it seems to be skipping over 0 and starting from 1 instead. Can someone please assist me in understanding how this works? showAnime = () => { let counter ...

Learn how to implement interconnected dropdown menus on an html webpage using a combination of JavaScript, AngularJs, and JSON dataset

Incorrect HTML code example: <div ng-app="myApp" ng=controller="myCtrl"> States : <select id="source" name="source"> <option>{{state.name}}</option> </select> Districts: <select id="status" name="status"> ...

Validating forms in React with Material-UI using hooks

Currently, I am working on a Next.js project that utilizes Material-UI as the primary UI framework. For validation purposes, I am implementing a React hooks form. Within my main component, I have the form structure with separate child components for vari ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Interactive sidebar search component for Angular

Within my angular application, I have implemented a universal sidebar navigation directive that offers a variety of features, including a comprehensive search function for users (with multiple criteria, not just a simple text input). When a user performs ...

Is it advisable to tidy up handlePress variables within useEffect?

As a newcomer to react native, I find myself struggling with figuring out which objects need to be cleaned up before a component unMount. I understand that API calls should be cleaned, but what else? For example, if I have a button like this: const _rende ...

The issue of race condition in Node.js programming

I've been diving into the documentation, but I'm struggling to figure out what's going on here. I have two functions: one downloads a CSV file via a URL, and the next function takes that CSV file and converts it to JSON FileDownload.js co ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

difficulty displaying an image sourced from a URL string within a JSON file in SwiftUI

In my SwiftUI file called ContentView.swift, I have the following code: struct Nasa_data: Codable { var copyright: String var date: Int var explanation: String var hdurl: String var media_type: String var service_version: String ...

Retrieve the ID of a specific row within a table in a datatables interface by selecting the row and then clicking a button

My goal is to have a table displayed where I can select a row and then have the option to edit or delete that row with a query. To achieve this, I need a primary key that won't be visible to the user. This is how my table is set up: <table id=&apo ...

Sequelize Error: Object A is not linked to Object B in Node.js

Two models exist: Question and Answer. Each answer has a question_id, and a question can have multiple answers. I am trying to include all the answers for each question in my JSON response but keep encountering an error: "message": "answe ...

Updating multiple documents in Mongoose that have a specific element in an array

I have structured a Mongoose schema like this: const mongoose = require('mongoose'); const ItemSchema = mongoose.Schema({ id: { type: String, required: true, }, items: { type: Array, required: true, }, date: { type: ...

Blending an HTML jQuery toggle

Is there a way to make the current headline fade out while simultaneously fading in a new one when switching to the next div using a jQuery .html switch? Check out the codepen example: https://codepen.io/balke/pen/JpNNve $(window).scroll(function() { ...

Integrate several YouTube players within a tabbed angular-ui system. Looking to incorporate a collapse feature

I come to you with a humble request for guidance. As a newcomer to Angular and someone who has never ventured into the realm of the YouTube JavaScript API, I am well aware that I may be making errors without even realizing it. While my code appears to be f ...

Ways to manage the order of RequestExecutor execution

I have recently developed an intranet site using SharePoint Office 365. Within the master page file, there is a menu bar that utilizes a List to store the URL and name. My goal is to control the visibility of the "Admin" button based on whether the user ...

Populate a pandas dataframe with predefined values

I currently have a pre-defined dataframe called df1: import pandas as pd df1 = pd.DataFrame(columns = ["id", "col_a","col_b","col_c"]) Additionally, I possess a JSON file: {'123': {'col_a': 5, 'col_b': "kuku", 'col_c&ap ...

What do you think of the unique JSON syntax found in the React-Redux-Firebase documentation? Valid or not?

The React-Redux-Firebase documentation showcases a sample code snippet. import { compose } from 'redux' import { connect } from 'react-redux' import { firebaseConnect, populate } from 'react-redux-firebase' const populates = ...