What is a more streamlined approach to creating a series of methods and functions that alter a single variable consecutively?

My JavaScript project involves handling sub-arrays within a long data file that cannot be altered. The data, stored in a variable named data, is retrieved via a script tag with a specified URL property. I need to extract and modify specific sub-arrays from this data but without changing the overall structure of the data itself, which is not entirely JSON-like.

In the code snippet below, I demonstrate the process of extracting "Yes" responses from "Question_5" of a survey and storing them in an array called q5_yes. While the existing code accomplishes this task, I am interested in optimizing it for efficiency and reusability since I will be performing similar operations frequently in the future.

To streamline the process, I have devised a function that encapsulates the steps required to retrieve the desired values for any given question and answer combination. By using this function, I can avoid duplicating code and simplify the extraction process for different data entries.

The function, named getQuestion, iterates through the data structure to find the specified question and answer pairs, filters out any undefined values, removes unnecessary entries, and flattens the resulting arrays for easy access.

For example, by calling getQuestion('Question_5', 'Yes'), I can efficiently extract the "Yes" responses for "Question_5" and store them in a new variable for further processing.

Answer №1

To ensure the desired mapping is at the 0th index of each array within the given problem context, follow these steps:

var data = {
  "reSEQ": [{
    "Entry_1": "Nov-2015",
    "Question_5": [{
        "Yes": 30
      },
      {
        "No": 5
      },
      {
        "Not Sure": 13
      },
      {
        "Total": 48
      }
    ],
    "Question_6": [{
        "Yes": 30
      },
      {
        "No": 5
      },
      {
        "Not Sure": 13
      },
      {
        "Total": 48
      }
    ]
  }]
};

var q5_yes = data.reSEQ[0].Question_5[0].Yes;

document.getElementById("foo").innerHTML = q5_yes;
<div id="foo">test</div>

Answer №2

function fetchAnswers(question, answer){
var arrayContent = data.reSEQ.map(function(element) {
return element[question].map(function(el) {
return el[answer];
});
});
arrayContent = arrayContent.map(function(subarray) {
return subarray.filter(function(value) {
return value !== undefined;
});
});
arrayContent = arrayContent.splice(0, arrayContent.length - 2); //remove current & lifetime entries
arrayContent = [].concat.apply([], arrayContent);

return arrayContent
}

var q5Values = fetchAnswers('Question_5', 'Yes') // retrieve the desired values as an array

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

Issues arise when attempting to make a SOAP request in NodeJS, as opposed to PHP where it functions seamlessly

As I work on integrating a SOAP-API to access data, I encounter an error when trying to implement it in my ExpressJS-Service using NodeJS. The API documentation provides examples in PHP, which is not my preferred language. My PHP implementation works flawl ...

Crack open a JSON object

I am struggling to parse a JSON object. It seems like the code is not working, can you help me? var mock_data = { "available": [{ "UserID": 7, "UserName": "Manoj", "Language": "Java", "Score": 9, "TimeLimit": 4.0 }, { "UserID ...

Is it possible for the 'error' attribute to be deemed invalid or inappropriate within ajax?

I am encountering an issue with my mobile cordova application. When attempting to log in, I am facing the following error: Error: JavaScript runtime error - Object doesn't support property or method 'error' The error is being traced back t ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...

Using JavaScript for Text Processing on Disk

Currently, I have a set of HTML files that require automated processing such as regex replacements and more complex actions like copying specific text blocks from one file to another. I am considering creating a series of scripts to handle this processing ...

Parsing a JSON array using Moment.js within a subscription function

I have a series of time entries within a data JSON array that I need to parse and format using Moment.js. The formatted data will then be stored in the this.appointmentTimes array for easy access on my view using {{appointmentTime.time}}. Here is the JSON ...

Approach for fetching these JSON records

I am currently exploring ways to retrieve all entries within a JSON payload using JavaScript. Specifically, I am interested in finding the best method to extract all instances of "o4" in a specific order (-159, -257). How can this be achieved? { ...

Issues with Google maps are causing multiple maps to malfunction

After incorporating some jquery code to create multiple maps upon window load, I noticed a peculiar issue with the maps - they all display the same location despite having different latitudes and longitudes set. Upon inspecting the code responsible for cr ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

Developing unit tests for a module responsible for generating Json REST services

Just completed working on https://github.com/mercmobily/JsonRestStores. Feeling a bit nervous since I haven't written any unit tests yet. This module is quite complex to test: it enables the creation of Json REST stores and direct interaction with th ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Failure to retrieve blob - net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK)

My fetch request code in my front end for a node js express web app hosted on MS Azure works well for small zip file blobs. However, it times out and displays the error net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK) when dealing with large blobs. ...

Performing an AJAX request to the database when a change occurs, prior to submitting the

In my user setup/create form, I am including a field for the users' license/certification number which needs to be validated and returned to a specific DIV Onchange before the form is submitted. I have heard that using AJAX POST is the way to achieve ...

Capturing Data from Tables and Saving it with Protractor

Imagine having a table structured like this <h2>HTML Table</h2> <table> <tr> <th>Company</th> <th>Contact</th> <th>Code</th> </tr> <tr> <td>Alfreds Fu ...

Unable to successfully update DIV content in JavaScript due to incorrect file path specified

I came across this code online and it seems to be functioning properly. However, no matter what name I give the file that is supposed to load into the DIV, I consistently receive an error message stating "Object was not found." What specific steps do I nee ...

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

Trouble with highlighting the chosen menu item

I have been attempting to implement this code snippet from JSFiddle onto my website. Although I directly copied the HTML, used the CSS inline, and placed the Javascript in an external file, the functionality does not seem to be working properly. Feel free ...

Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues ...

"Utilizing ng class with an array of objects: A step-by-step guide

I am facing a scenario in which my response appears as follows: "currency" : [ { "_id" : ObjectId("584aad5d3e2537613e5f4c39"), "name" : "USD" } ], I need to enable my checkbox based on the currency name. I attempted the followi ...

Guide to Dynamically Including an Element in an Array using Typescript

Encountering a type error within the <RenderFormFields formFields={formFieldsData} /> component:- Types of property 'type' are not compatible. Type 'string' cannot be assigned to type '"select"'.ts(2322) Rende ...