Obtain JSON value based on changing state in React Native

After receiving a JSON from an API, I store it in this.state.data as shown below:

[
  {
    "name": "Primary Category",
    "value": [
      {
        "value": "Fracture",
        "Diagnosis_Code": ["DIAG003"],
        "name": "Primary Category",
        "FK_Diagnosis_Content_ID": 3,
        "FK_Diagnosis_Category_ID": 1
      },
      {
        "value": "Osteoarthritis",
        "Diagnosis_Code": ["DIAG001"],
        "name": "Primary Category",
        "FK_Diagnosis_Content_ID": 1,
        "FK_Diagnosis_Category_ID": 1
      },
      {
        "value": "Osteonecrosis",
        "Diagnosis_Code": ["DIAG002", "DIAG004"],
        "name": "Primary Category",
        "FK_Diagnosis_Content_ID": 2,
        "FK_Diagnosis_Category_ID": 1
      }
    ]
  },
  {
    "name": "Anatomy",
    "value": [
      {
        "value": "Hip",
        "Diagnosis_Code": ["DIAG001"],
        "name": "Anatomy",
        "FK_Diagnosis_Content_ID": 4,
        "FK_Diagnosis_Category_ID": 2
      },
      {
        "value": "Pelvis",
        "Diagnosis_Code": ["DIAG002", "DIAG003", "DIAG004"],
        "name": "Anatomy",
        "FK_Diagnosis_Content_ID": 6,
        "FK_Diagnosis_Category_ID": 2
      }
    ]
  }
]

I am using a dynamic state handling function like the one below:

onChangeTextPress(key, value){
  this.state.selected[key] = value
  //another code
}

The example of this.state.selected is

[ 'Primary Category': 'Fracture', Anatomy: 'Hip']

I want to extract the values of FK_Diagnosis_Content_ID based on the keys and values stored in this.state.selected.

For example, given the current content of selected, the expected result would be: [3, 4]

This output is derived by matching the key-value pairs in the JSON data with the corresponding entries in the this.state.selected object. In this case, it relates to the name and value fields.

If more clarification is needed, please feel free to ask any questions.

I appreciate any help or insights provided.

Answer №1

If you're looking to utilize the power of Object.keys() and Array.prototype.includes(), here are some samples that demonstrate their usage.

Example 1

// Assume we have the following data structure
const data = { 'Primary Category': 'Fracture', Anatomy: 'Hip' }

Object.keys(data).forEach((key) => console.log(key))
// Output: 
// Primary Category
// Anatomy

To retrieve the desired value, consider the following approach:

Example 2

// Assuming this.state.selected contains { 'Primary Category': 'Fracture', Anatomy: 'Hip' }
const keys = Object.keys(this.state.selected);
const result = [];
this.state.data.forEach((d) => {
  if(keys.includes(d.name)) { 
    d.value.forEach((v) => {
      if(v.value === this.state.selected[d.name]) {
        result.push(v['FK_Diagnosis_Content_ID']);
      }
    })
  }
});
console.log(result);
// Output: [3,4]

Example 3

// Assuming this.state.selected is [{ 'Primary Category': 'Fracture'}, {Anatomy: 'Hip' }]
// Since each object contains only one key
const keys = this.state.selected.map((s) => Object.keys(s)[0])
const result = [];
this.state.data.forEach((d) => {
  if(keys.includes(d.name)) { 
    d.value.forEach((v) => {
      if(v.value === this.state.selected[keys.indexOf(d.name)][d.name]) {
        result.push(v['FK_Diagnosis_Content_ID']);
      }
    })
  }
});
console.log(result);
// Output: [3,4]

Answer №2

Utilize this code snippet in your project:

const keys = Object.keys(this.state.selected);
const result = [];
this.state.data.forEach((item) => {
  if (keys.includes(item.tag)) { 
    item.value.forEach((val) => {
      if (val.value === this.state.selected[item.name]) {
        result.push(val['FK_Diagnosis_Content_ID']);
      }
    });
  }
});
console.log(result);

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

Solving repeated function firing with ng-checked in an AngularJS ng-repeat loop

In the HTML code below, there is an ng-repeat that creates checkboxes: <span ng-repeat="name in $ctrl.widgetSelectorNames" class="widget-selectors"> <label class="checkbox" for="{{name}}"> <input type="checkbox" value="{ ...

Learning the process of connecting functions to events

// param {id:'buttonId', action : function(event[,param1, param2] ){}, behavior:function(event[,param1, param2] ){} } CustomButton = function(parameters) { var buttonElement = document.getElementById(parameters.id); // how c ...

Make sure that the function displays the output once it has been received using the jQuery.get method

This script fetches data using the $.get method from an XML file on an ASP ashx server: $.get("http://www.example.com/example.ashx", { From: txtFrom, To: txtTo, Date: txtTime }, function (data) { var arr ...

Tips for resolving: Alert: React does not allow functions as a child component

I recently made an update to my router configuration to support a second main route. import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; // Components & Pages // Home import HomePag ...

Obtain HTML controls in the code-behind of an ASP.NET application

Is it possible to access HTML changes made with JavaScript in ASP.NET code behind? I came across some dhtml "drag and drop" code online (), but I'm struggling to access the updated controls in my code behind after moving items between lists. I attem ...

I am attempting to expand an array of objects divided into two distinct inputs within a React component

There is an array of objects named estimate, with keys 'cost' and 'service'. By clicking 'Add', a new index (i) can be added to the array. The problem arises on the first cycle where {'cost': 2500, 'service&apos ...

Showcasing JavaScript variable in HTML with Vue.js

How can I use Vue.js to display the first name, last name, etc. data retrieved from the getData function? Right now, I am passing a blank array to display this information next to the getData function, but I need to pass the actual values returned by the g ...

Tinymce editor does not display icons as expected

I am attempting to create a custom styled list that is editable with tinymce. The list-items are using Material-Check-Icons as bullet-points, which are added as css-pseudo-elements ::before. This setup works well, but when I integrate tinymce (v5) into the ...

What is the process for adding information to datatables using jQuery?

I have been struggling to make a data table in jQuery function correctly. I am able to append data to the table, but the sorting, pagination, and search features are not working. Even though the data is visible in the table, it shows as 0 records. I am wor ...

text field remaining populated

I have a form where the input fields clear when they are clicked on. It works well on most pages, but there is a specific type of page where it is not functioning properly due to the presence of another javascript running. - issue observed // On this pa ...

Align the content to the right and center it within the table

One common issue I face is working with tables that contain numbers requiring right alignment to ensure the ones/tens/hundreds/thousands places line up correctly. Here's an example: 2,343 1,000,000 43 43,394 232,111 In these tables, ...

Utilizing map in React JS to simultaneously execute various functions

Currently, I am working on parsing an array in React JS. Here is an example of my array (it can change dynamically): [ "save", "save", "not", "save"] The objective is to create a function that triggers another funct ...

IBM MobileFirst 8 Java Adapter does not currently support JSON data containing arrays in the request body

We are currently facing a problem with an IBM MobileFirst 8 Java adapter. When we send simple JSON data to the adapter, it works fine: {"id":2, "priority": 45} However, when we send more complex JSON data like this: {"id":2, "priority": 45, "list": [{"m ...

Create a copy of a div element once the value of a select element has

After modifying a select option, I'm attempting to replicate a div similar to the example shown in this link: http://jsfiddle.net/ranell/mN6nm/5/ However, instead of my expected lists, I am seeing [object]. Any suggestions on how to resolve this issue ...

Cut down the length of an audio clip with javascript (beginning 3 seconds)

Is it possible to cut a portion of my audio file that was recorded using JavaScript? Specifically, I would like to trim the first 3 seconds. The audio was recorded using p5.js and then combined with karaoke audio using AudioContext(). I need to trim it b ...

X-ray Picker failing to retrieve a value

I am currently using the most recent version of the x-ray npm module in the code snippet below. Despite my expectations, the Meta and Metatags elements remain empty when I print out obj. Can anyone help me identify what I might be missing? var Xray = req ...

Changing the position of elements dynamically in Javascript by altering their absolute positioning

I am working on an HTML page that contains a div positioned absolutely. My goal is to use Javascript to dynamically move this div downward whenever some data preceding it is generated. I have been experimenting with the .css jQuery function but unfortunate ...

Is it possible to precisely position multiple children in a relative manner?

I am currently developing a custom dropdown menu where I want the parent element to be relatively positioned within the page. The goal is for all the child elements of the dropdown menu (the list items) to appear as if they are part of a select element and ...

Investigate the presence of a vertical scrollbar using JQuery or JavaScript

Within an HTML report, I have applied the style "overflow:auto" to allow for dynamic data filling. I am now facing the challenge of detecting whether a vertical scrollbar exists within the report. After scouring various forums for solutions, I came across ...

Troubleshooting Problems with File Upload Response in ASP.Net MVC Ajax.BeginForm

I have implemented a modal feature that allows users to upload a file. I am looking for a JSON response to indicate whether the upload was successful or not, and then display this information to the end user. Here is my current View: @model int <div ...