Extract specific data from JSON objects

I have a JSON string that I need to parse on the client side in order to extract data for three different column names (MAT_ETHNICITY, PAT_ETHNICITY, SEX). My goal is to populate drop down lists with the values. Should I handle this by making three separate SQL calls and sending the data via three server calls, parsing it server-side, or parsing it client-side using a loop? Thank you.

[
    {
        "REFCODE": "HIS",
        "DESCRIPTION": "Hispanic or Latino",
        "COLUMN_NAME": "MAT_ETHNICITY"
    },
    {
        "REFCODE": "NHIS",
        "DESCRIPTION": "Not Hispanic or Latino",
        "COLUMN_NAME": "MAT_ETHNICITY"
    },
    {
        "REFCODE": "UNK",
        "DESCRIPTION": "Unknown",
        "COLUMN_NAME": "MAT_ETHNICITY"
    },
    {
        "REFCODE": "AMERIND",
        "DESCRIPTION": "American Indian/Alaska Native",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "ASIAN",
        "DESCRIPTION": "Asian",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "HAW",
        "DESCRIPTION": "Native Hawaiian or Other Pacific Islander",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "AA",
        "DESCRIPTION": "Black or Africian American",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "WHITE",
        "DESCRIPTION": "White",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "MORE",
        "DESCRIPTION": "More than one race",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "UNK",
        "DESCRIPTION": "Unknown",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "M",
        "DESCRIPTION": "Male",
        "COLUMN_NAME": "SEX"
    },
    {
        "REFCODE": "F",
        "DESCRIPTION": "Female",
        "COLUMN_NAME": "SEX"
    }
]

Answer №1

To store the values from a JSON array into separate arrays, you can utilize array mapping:

var refArr = jsonObj.map(function(ele){return ele.REFCODE;})
var descArr = jsonObj.map(function(ele){return ele.DESCRIPTION;})
var colNameArr = jsonObj.map(function(ele){return ele.COLUMN_NAME;})

Each map function will iterate through the JSON array and extract the values to populate their respective arrays.


EDIT: After reviewing your comments, it seems there was confusion regarding the values you wanted. Based on your clarification:

... SEX, PAT_ENTICITY and MAT_ETHNICITY rather than REFCODE, DESCRIPTION and COLUMN_NAME. This means sexArr = ["Female","Male"] and MAT_ETHNICITY would be var matArr=["Hispanic or Latino", "Not Hispanic or Latino"] etc? or is looping a better approach?

You could use .map for those specific value arrays, but remember to handle undefined or empty string values if using mapping since it returns elements equal to the input array length.

A more suitable method may involve iterating with .forEach(...) as shown below:

var sexArr = [];
var patArr = [];
var matArr = [];

jsonObj.forEach(function(ele){
  switch(ele.COLUMN_NAME){
    case "SEX":
      sexArr.push(ele.DESCRIPTION);
      break;
    case "PAT_ETHNICITY":
      patArr.push(ele.DESCRIPTION);
      break;
    case "MAT_ETHNICITY":
      matArr.push(ele.DESCRIPTION);
      break;
    default:
      //handle additional cases if needed
      break;
  }
});

The code snippet above transforms the provided array into the following:

//matArr
["Hispanic or Latino", "Not Hispanic or Latino", "Unknown"]

//patArr
["American Indian/Alaska Native", "Asian", "Native Hawaiian or Other Pacific Islander", "Black or African American", "White", "More than one race", "Unknown"]

//sexArr
["Male", "Female"]

Answer №2

If you want to improve the speed of your website, it's advisable to reduce the number of server calls. In JavaScript, splitting this data into three separate arrays is a simple task.

var data = [...], // Original array
    refCodes = [],
    descriptions = [],
    columns = [],
    parseData;

parseData = function () {
    var ref,
        desc,
        col,
        i,
        l;

    for (i = 0, l = data.length; i < l; i++) {
        ref = data[i]['REFCODE'];
        desc = data[i]['DESCRIPTION'];
        col = data[i]['COLUMN_NAME'];

        if ($.inArray(ref, refCodes) === -1) {
            refCodes.push(ref);
        }
        if ($.inArray(desc, descriptions) === -1) {
            descriptions.push(desc);
        }
        if ($.inArray(col, columns) === -1) {
            columns.push(col);
        }
    }
};

By implementing this code, you will have access to unique values within each array.

Answer №3

Here's a helpful technique that can be adjusted to suit your needs

var data = [{"REFCODE":"HIS","DESCRIPTION":"Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"NHIS","DESCRIPTION":"Not Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"AMERIND","DESCRIPTION":"American Indian/Alaska Native","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"ASIAN","DESCRIPTION":"Asian","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"HAW","DESCRIPTION":"Native Hawaiian or Other Pacific Islander","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"AA","DESCRIPTION":"Black or Africian American","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"WHITE","DESCRIPTION":"White","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"MORE","DESCRIPTION":"More than one race","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"M","DESCRIPTION":"Male","COLUMN_NAME":"SEX"},{"REFCODE":"F","DESCRIPTION":"Female","COLUMN_NAME":"SEX"}];

function shallowClone(obj, exclude) {
  var clone = {};
  for (var prop in obj) {
    if (prop != exclude) {
      clone[prop] = obj[prop];
    }
  }
  return clone;
}

function mapFromArray (list , keyByProp, excludeKeyByProp) {
  var map = {};
  for (var i=0, item; item = list[i]; i++) {
    if ( !map[item[keyByProp]] ) {
      map[item[keyByProp]] = [];
    }
    map[item[keyByProp]].push(item);
  }
  
  if (excludeKeyByProp) {
    for (var prop in map) {
      map[prop] = map[prop].map(function(obj){
        return shallowClone(obj, keyByProp);
      });
    }
  }
  return map;
};


var separated = mapFromArray(data, 'COLUMN_NAME', true);
console.log(separated);
var pre = document.body.appendChild(document.createElement('pre'));
pre.innerHTML = JSON.stringify(separated, null, 2);

Prior to stating your specific output requirement in a comment, I provided this solution

This answer by krillgar is effective. It avoids being O(n2) and ensures no duplicates.

var data = [/*your data */];
var refCodes = {}, descriptions = {}, columns = {};
for (var i = 0; i < data.length; i++) {
    refCodes[data[i].REFCODE] = true;
    descriptions[data[i].DESCRIPTION] = true;
    columns[data[i].COLUMN_NAME] = true;
}

refCodes = Object.keys(refCodes);
descriptions = Object.keys(descriptions);
columns = Object.keys(columns);

Additionally, here is a more general version of the above code

var data = [{"REFCODE":"HIS","DESCRIPTION":"Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"NHIS","DESCRIPTION":"Not Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"AMERIND","DESCRIPTION":"American Indian/Alaska Native","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"ASIAN","DESCRIPTION":"Asian","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"HAW","DESCRIPTION":"Native Hawaiian or Other Pacific Islander","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"AA","DESCRIPTION":"Black or Africian American","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"WHITE","DESCRIPTION":"White","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"MORE","DESCRIPTION":"More than one race","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"M","DESCRIPTION":"Male","COLUMN_NAME":"SEX"},{"REFCODE":"F","DESCRIPTION":"Female","COLUMN_NAME":"SEX"}];

function makeArraysFromProps(data) {
  var map = {};
  for (var i = 0; i < data.length; i++) {
    var keys = Object.keys( data[i] );
    for (var j = 0; j < keys.length; j++ ) {
      var key = keys[j];
      if (!map[key]) {
        // First mapping to prevent duplicates without an O(n2) complexity
        map[key] = {};
      }
      map[key][ data[i][key] ] = true;
    }
  }
  var mapKeys = Object.keys(map);
  for (var k=0; k < mapKeys.length; k++) {
    map[mapKeys[k]] = Object.keys(map[mapKeys[k]]);
  }
  return map;
}


var separated = makeArraysFromProps(data);
console.log(separated);
var pre = document.body.appendChild(document.createElement('pre'));
pre.innerHTML = JSON.stringify(separated, null, 2);
var separated = makeArraysFromProps(data);
console.log(separated);

document.body.appendChild(document.createTextNode(JSON.stringify(separated)))

Answer №4

Why waste time with multiple SQL calls when you can achieve what you need with just one call? Simply parse the data client-side and populate your dropdown using JavaScript.

As for extracting the data, you can create an object to store the values you want and loop through it as needed. Here is a simple way to do that:

var json = YOURJSONOBJECT;

var patObj = new Object;

json.forEach(function(data, i){ 
  if(data.COLUMN_NAME == 'PAT_ETHNICITY') {
    patObj[i] = { refCode: data.REFCODE, description: data.DESCRIPTION }
  }
  // Add other columns here
});

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

Update your Electron application with the npm update command

I have recently published an app on a local npm repository, and this particular app serves as a crucial dependency for my second electron application. The electron app I am working on is structured around node_modules/my-first-app/dist/index.html. I am w ...

Step-by-step guide to uploading files using cucumber-js

Is there a way to write a script that can successfully fill out a form and upload a file using cucumber-js, selenium, and protractor? I am encountering an issue where there is no xpath/id available to click on when trying to upload a file. How have you d ...

Why isn't my lightbox able to read this specific property?

A gallery was created using both lightgallery and cycle2. Cycle is a carousel plugin while lightgallery is a lightbox gallery. Clicking on an image in the carousel opens it in the lightbox. Everything worked perfectly until a category in the carousel was ...

The properties are not appearing on the screen nor in the React Development Tools

Having difficulties grasping React props and mapping data from an array? Struggling to get the props to show up on your Card component, or display in React dev tools? It's unclear where the mistake lies. Seeking assistance to pinpoint the issue. Also ...

PHP makes it simple to decode JSON into an associative array, complete with numbering for

I am working with JSON data that is dynamically generated by SimpleXML from an XML file: "{"description":"Testing","site":"http:\/\/localhost","steps":{"step":[{"command":"grabimage","parameter":"img[alt=\"Next\"]"},{"command":"click", ...

Enhance the efficiency of your JavaScript code by minimizing repeated selectors

I've been working on a JavaScript project where I came across the following lines of code: $('#content').on('click', 'input[type=submit]', function(){ $('#content').on('click', 'a.removebutton&a ...

Javascript - Transforming tabular information into a hierarchical tree structure (JSON)

When extracting JSON data from a table, the format typically resembles the following simplified structure: https://i.sstatic.net/eqfXM.png The JSON format obtained might look like this: const myObjOriginal = { "rows": [{ "name": "row 1", "cell ...

Trigger an action in the clean-up function of useEffect

I am facing an issue with a form component in a Material UI <Tab /> where users can update their address information. The data is fetched from the API using redux-thunk, and the form fields are pre-filled with server data before the update occurs. h ...

Utilizing amCharts Postprocessing for fetching data for visual representation

My goal is to utilize amcharts for displaying data retrieved from my server. Unfortunately, the API format doesn't align directly with amCharts. It seems that I need to utilize the postProcess function to preprocess the data, but I am struggling due t ...

React - Implementing dynamic component rendering on a webpage

My component, Item.js, is static. Routes.js export default () => ( <Provider store={store}> <BrowserRouter> <Switch> <Route path="/posts" component={Posts} /> <Route path="/form" component={Postfo ...

The dynamic alteration of BackgroundImage does not appear to be functioning correctly with tailwind and nextjs

Introduction While working on my weather application using nextJS and TailwindCSS, I encountered a UI issue towards the end of development. Unfortunately, I couldn't resolve this problem alone. My main concern is changing the background image dynami ...

Display JSON element in Angular only once

Below is the code snippet: <ion-content padding> <h1>Datum: </h1> <ion-list> <ion-item *ngFor="let u of tecaj"> <h2>{{u.datum}}</h2> <h2>{{u.drzava}} | {{u.valuta}}</h2> ...

How to pass an axios-retrieved array prop to a child component in a Laravel Vue SPA?

How can a Laravel Vue SPA pass an array prop retrieved by axios to a child component? The json object from somedomain.com/channellist is fetched using axios and needs to be passed to the child component. What's the best way to ensure that activeChan ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

What is preventing me from applying a jQuery function to an ng-click event in AngularJS?

Seeking clarity on why I am receiving the result of undefined when attempting to construct an ng-click call to a method using a jQuery function. Here's a specific example: <a href="#" class="btn btn-default" ng-click="angularMethod($('input[ ...

Tips for sending icons as properties in React using TypeScript

Recently diving into typescript, I embarked on a straightforward project. Within this project lies a sidebar component that comprises multiple sidebarNavigationItem components. Each of these Sidebar items consists of an Icon and Title, showcased below. Si ...

Activate the class only on the current element

I need help with a specific functionality on my website. I have multiple sections with content and buttons, and when a button is clicked, I want to add an active class to the corresponding content section within the same row. <div id="1" class="row"> ...

`Next.js project experiencing issues with scroll trigger functionality`

I've been working on a gsap animation with a scroll trigger, and while the animation itself functions fine, it's not triggering as expected. The AnimationEffect code involves using gsap and scrolltrigger to create the animation. The Hero section ...

Trouble getting search filter to function properly on an array of objects in a Vue JavaScript application

Can someone help me with integrating this code into my project? Here is the code I am referencing: http://jsfiddle.net/dkmmhf5y/701/ This snippet shows my JavaScript file, please disregard the 'test' data var app = new Vue ( { el: &apos ...

Achieve Vue to refresh the view or component

I am facing a dilemma while working on a specific component. The component in question is called "RecentUpdates". Within this component, I am passing props down to several other components, as indicated at the beginning of the file. My issue arises when ...