Retrieving data from a JSON object using JavaScript

{
   "questions_id":[
      "7",
      "9",
      "2"
   ],
   "select_param_type":[
      "is greater than",
      "is less than",
      "is less than"
   ],
   "select_param_value":[
      "2",
      "4",
      "2"
   ],
   "radio_type":[
      "and",
      "or",
   ]
}

I want to interpret the JSON data in this sequence:

questions_id, select_param_type, select_param_value, radio_type
.

An example format would be:

["7", "is greater than", "2", "and", "9", "is less than", "4", "or", "2", "is less than",  "2" ]

The radio_type acts as the connection point between different Array levels.

Any suggestions on how I can accomplish this task?

Thank you.

Answer №1

If you have an array of keys and need to retrieve the value associated with a specific index, you can do so by mapping the index to the corresponding value in the array. Remember to remove any trailing undefined values at the end.

var data = { questions_id: ["7", "9", "2"], select_param_type: ["is greater than", "is less than", "is less than"], select_param_value: ["2", "4", "2"], radio_type: ["and", "or"] },
    order = ['questions_id', 'select_param_type', 'select_param_value', 'radio_type'],
    result = [],
    i = 0;

do result.push(...order.map(k => data[k][i]));
while (data.radio_type[i++])

result.pop();

console.log(result.join(' '));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Here is a solution for you

let jsonData = {
   "questions_id":[
      "7",
      "9",
      "2"
   ],
   "select_param_type":[
      "is greater than",
      "is less than",
      "is less than"
   ],
   "select_param_value":[
      "2",
      "4",
      "2"
   ],
   "radio_type":[
      "and",
      "or",
   ]
};

let orderingKey = ["questions_id", "select_param_type", "select_param_value", "radio_type"];

let finalResult = [];

orderingKey.map(key => {
  finalResult.push(...jsonData[key]);
});

console.log(finalResult);

Iterate through the orderingKey array to access the keys and use the spread operator to combine the values of those keys.

Answer №3

Give this code a try

const data = {
    "questions_id":[
        "12",
        "5",
        "8"
    ],
    "select_param_type":[
        "is equal to",
        "contains",
        "starts with"
    ],
    "select_param_value":[
        "apple",
        "xyz",
        "abc"
    ],
    "radio_type":[
        "and",
        "or",
    ]
}

const categories = ["questions_id", "select_param_type", "select_param_value", "radio_type"];

let finalResult = [];

categories.map((category, idx) => {
    for(let entry in data) {
        if (data[entry][idx]) {
            finalResult.push(data[entry][idx])
        }
    }
});

console.log(finalResult);

The output will be

["12", "is equal to", "apple", "and", "5", "contains", "xyz", "or", "8", "starts with", "abc" ]

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

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

Locate the destination URL in Fancybox

Is there a way to insert a link into the title, using the selected anchor's href but with an added prefix? I need help figuring out how to achieve this. Specifically, I am looking to access this.href on the chosen anchor element. $(".gallery-module & ...

Jackson: decoding nested arrays

Trying to make sense of this nightmare JSON... [ ["X", "Y", 0.00010919, 0, null, null, null], ["X", "Y", 0.00210919, 0, null, null, null], ["A", "B", 0.00310919, 0, null, null, null] ] I'm having trouble getting Jackson to properly parse it and m ...

Transferring PHP variables to Javascript variables

I'm working on a basic php script that updates specific elements of a game through JavaScript. I've encountered an issue where the variable data doesn't seem to transfer when passing them from the script to the game using forms. Currently, t ...

How to Customize the Navbar Position in Bootstrap 3 when the Brand/Logo is Collapsed

I am currently in the process of creating my first website and experimenting with the Bootstrap 3 framework. The navbar I have selected is designed to adjust based on screen size, collapsing into a small button for use on tablets and mobile devices. Howe ...

Is there a way to link dynamic server fields with VueJS?

How can I bind data posted by the server with Vue.js in order to display the data instead of field names? <script> module.exports = { data: function () { return { filedNameFromServer: ['{{filed1}}' ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Exercises from the Shader Scriptures

This winter break, I have dedicated my time to delving into the world of shaders. I am currently faced with a challenging exercise: y = sin(x); Explore the exercises below and observe the results: Introduce time (u_time) into the equation before calcul ...

Struggling to grasp the concept of Linked lists in the C language because of a lack of comfort with Pointers? Just take it slow and steady as a beginner

After completing two chapters on 'Pointers' in a book, I find myself in need of more practice with certain sub-topics. These include using pointer notations instead of array notations and working with arrays of pointers to some extent. I have a ...

Trouble with React Material Select Options Failing to Populate

After iterating and producing MenuItems, I am able to see the items when I console.log, but in the UI, the dropdown appears empty. I'm puzzled as to why the Select's are not being populated. Any thoughts on this issue? Below is the supplied code ...

Deciphering intricate JSON values using the Lift-JSON library

In my Scala 2.12 project, I am attempting to utilize Lift-JSON for parsing a configuration file named myapp.json. The contents of the config file are as follows: { "health" : { "checkPeriodSeconds" : 10, "metrics" : { "stores" : { ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Issue: It seems like there is an error with using functions as a React child. Uncertain about the exact location

This specific issue is one of the two errors I have come across in the same application referenced in my previous inquiry. The first error encountered is as follows: Warning: Functions are not valid as a React child. This may occur if you mistakenly return ...

Transferring information between functions

I am trying to retrieve the value of my drop-down within the getData function. Although the data displays correctly in the run function, I am unsure of how to pass that data down to the getData() function. <select class="form-co ...

Executing a series of AJAX requests within a loop

I am looking for a way to optimize sending multiple AJAX calls simultaneously in Javascript/Angular. Despite my efforts to find a solution, I have come up empty-handed. My goal is to send all requests as quickly as possible without waiting for each one to ...

What is the best way to manage communication with a database in a Node.js application?

I have a specific structure in my Express app: There is a db helper that I use to interact with my MariaDB database Here is the code snippet: var MariaSQL = require('mariasql'); var db = new MariaSQL(); var queries = { getUserByID : &a ...

Updating Variables Declared in Parent Component from a Child Component in React using NextJS - A Comprehensive Guide

After reviewing the tutorial on React: Reverse Data Flow to update the variables foodObj, input, and buttonClicked declared in the Parent Component file Main.js, using the child component <SearchAndSuggestion>, I encountered an issue. Here is a snipp ...

Opt for utilizing a global npm package over repeatedly installing it

Is there a way to utilize the globally installed package without needing to reinstall it every time we run npm i? Here's the scenario I have: I've set up a docker image with a specific package already installed (installation command in the Docker ...

Arranging elements on top of a fixed element using JavaScript and CSS

Currently, I am implementing Javascript code that adds a div to the body of pages. The purpose of this div is to always stay at the top of the document or window, regardless of the page's design and content. Everything was functioning correctly until ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...