Loop through an array of objects that are in JSON format, make changes to them, and add new elements to them, all while utilizing

After pulling data from a database in JSON format and assigning it to the variable 'var tabs', here is how the formatted JSON looks:

[{
    "TAB_ID": "1",
    "TAB_NAME": "TAB ONE",
    "TAB_DISPLAY": "1",
    "QUESTIONS": [{
        "QUESTION_ID": 1,
        "QUESTION": "Question number one",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 2,
        "QUESTION": "Question number two",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 3,
        "QUESTION": "Question number six",
        "ANSWER": ""
    }]
}, {
    "TAB_ID": "1",
    "TAB_NAME": "TAB ONE",
    "TAB_DISPLAY": "1",
    "QUESTIONS": [{
        "QUESTION_ID": 1,
        "QUESTION": "Question number one",
        "ANSWER": "Some Other Answer"
    }, {
        "QUESTION_ID": 2,
        "QUESTION": "Question number two",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 3,
        "QUESTION": "Question number six",
        "ANSWER": "Some Still Different Answer"
    }]
}]

I am now tasked with iterating over this array and implementing the following logic:

For each QUESTION within the TAB, if the QUESTION has an ANSWER, I should append a key/value pair of "HAS_ANSWER": "1" to that QUESTION.

    {
        "QUESTION_ID": 1,
        "QUESTION": "Question number one",
        "ANSWER": "Some Other Answer",
        "HAS_ANSWER": "1"
    }

Despite extensive research on Underscore documentation and numerous examples, I can't seem to figure out how to approach this task efficiently.

My current understanding suggests leveraging nested _.map functions, but all examples I've encountered yield a subset of objects rather than the desired modification and extension within the existing JSON structure (array of objects).

Any assistance or guidance in tackling this challenge would be immensely appreciated.

Update:

By employing the snippet below:

data = _.map(data, obj => _.map(obj.QUESTIONS, q => {
    if (q.ANSWER) {
        q.HAS_ANSWER = 1;
    }
    return q;
}));

The script successfully iterates over the questions, making necessary modifications. However, it only returns an array of questions without retaining the original outer-layer TAB data:

    "TAB_ID": "1",
    "TAB_NAME": "TAB ONE",
    "TAB_DISPLAY": "1",

To resolve this, utilizing _.each for the outer array and _.map for the inner array is recommended:

data = _.each(data, obj => _.map(obj.QUESTIONS, q => {
    if (q.ANSWER) {
        q.HAS_ANSWER = 1;
    }
    return q;
}));

Note: The => syntax is only compatible with newer JavaScript implementations and not supported in Safari/Webkit browsers. Therefore, use the alternative syntax below for better cross-browser compatibility:

data = _.each(data, function(obj){
    _.map(obj.QUESTIONS, function(q){
       if (q.ANSWER) {
           q.HAS_ANSWER = 1;
       }
       return q;
    });
});

This modified approach aligns perfectly with the required outcome.

Answer №1

To achieve this task, you can utilize vanilla JavaScript with the help of Array#map.

// Loop through the data
data = data.map(obj => obj.QUESTIONS.map(q => {
    // Check if question has an answer and add `HAS_ANSWER` property 
    if (q.ANSWER) {
        q.HAS_ANSWER = 1;
    }
    
    // Update the question object
    return q;
}));

var data = [{
    "TAB_ID": "1",
    "TAB_NAME": "TAB ONE",
    "TAB_DISPLAY": "1",
    "QUESTIONS": [{
        "QUESTION_ID": 1,
        "QUESTION": "Question number one",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 2,
        "QUESTION": "Question number two",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 3,
        "QUESTION": "Question number six",
        "ANSWER": ""
    }]
}, {
    "TAB_ID": "1",
    "TAB_NAME": "TAB ONE",
    "TAB_DISPLAY": "1",
    "QUESTIONS": [{
        "QUESTION_ID": 1,
        "QUESTION": "Question number one",
        "ANSWER": "Some Other Answer"
    }, {
        "QUESTION_ID": 2,
        "QUESTION": "Question number two",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 3,
        "QUESTION": "Question number six",
        "ANSWER": "Some Still Different Answer"
    }]
}];

data = data.map(obj => obj.QUESTIONS.map(q => {
    if (q.ANSWER) {
        q.HAS_ANSWER = 1;
    }
    return q;
}));

console.log(data);
document.getElementById('output').innerHTML = JSON.stringify(data, 0, 4);
<pre id="output"></pre>


Equivalent code using Underscore/Lodash library

data = _.map(data, obj => _.map(obj.QUESTIONS, q => {
    if (q.ANSWER) {
        q.HAS_ANSWER = 1;
    }
    return q;
}));

Answer №2

By utilizing the Array.prototype.forEach() method in standard Javascript, the code could be structured like this:

tabs.forEach(tab => {
  tab['QUESTIONS'].forEach(question => {
    if (question['ANSWER']) {
      question['HAS_ANSWER'] = 1;
    }
  });
});

var tabs = [{
    "TAB_ID": "1",
    "TAB_NAME": "TAB ONE",
    "TAB_DISPLAY": "1",
    "QUESTIONS": [{
        "QUESTION_ID": 1,
        "QUESTION": "Question number one",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 2,
        "QUESTION": "Question number two",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 3,
        "QUESTION": "Question number six",
        "ANSWER": ""
    }]
}, {
    "TAB_ID": "1",
    "TAB_NAME": "TAB ONE",
    "TAB_DISPLAY": "1",
    "QUESTIONS": [{
        "QUESTION_ID": 1,
        "QUESTION": "Question number one",
        "ANSWER": "Some Other Answer"
    }, {
        "QUESTION_ID": 2,
        "QUESTION": "Question number two",
        "ANSWER": ""
    }, {
        "QUESTION_ID": 3,
        "QUESTION": "Question number six",
        "ANSWER": "Some Still Different Answer"
    }]
}];

tabs.forEach(tab => {
  tab['QUESTIONS'].forEach(question => {
    if (question['ANSWER']) {
      question['HAS_ANSWER'] = 1;
    }
  });
});

console.log(tabs);

This method directly modifies the existing data structure.

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

Struggling to Load: Ajax Request to Google App Engine Causing Page to

I have developed a page that communicates with a Python application running on Google App Engine to retrieve JSON data using JSONP for cross-origin functionality. However, I am encountering an issue where the page hangs and fails to display the data no mat ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

Discover Xml information or Json object displayed as XML tree in Html using Javascript

Looking for a way to display my JSON object or XML data in HTML similar to how React does it. I found this component on GitHub: https://github.com/marushkevych/xml-display-component, but I prefer not to mix JavaScript and React.js. Can anyone offer some gu ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

How can you determine if a string includes all the words listed in a multidimensional array?

I'm brand new to the world of coding but I have a specific goal in mind. Here's an example of the multidimensional array I'm working with: var requiredProducts = [{ product: 'PRODUCT 1', keywords: ['KEYWORD1', & ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

Tips for managing the react-bootstrap carousel using personalized buttons

In order to have control over carousel slides using custom buttons, I managed to achieve this with reference to this Example. Below is the code implementation: import React, { useState } from "react"; import { Carousel, Button, Container, Row } ...

Having trouble executing a node module on a Windows system?

I am encountering an issue while trying to run npm run start-dev. I have been unable to resolve it on my own and could use some assistance. Here is a screenshot of the problem: https://i.stack.imgur.com/Qx243.png ...

Is IPv6 like a JavaScript string in any way?

Introduction In the era of IPv4, life was simpler as IPv4 addresses could easily be converted into 32-bit integers for various calculations. However, with the introduction of IPv6, things have become more complicated due to the lack of native support for ...

Can you explain how to retrieve the information from this array in Swift that has been sent from PHP?

I am encountering issues with accessing the data within the Form array nested in the larger array structure: ["leagueStats": { Form = ( ( { date = "2017-01-31"; "player1_name" = Dicky; ...

Correct the JSON format which contains key-value pairs

After creating the following JSON data, I realized it wasn't formatted correctly. The issue is with the inverted quotes in the key message and in null. NSString *chID=@"101"; NSString *reqId=@"REQID"; NSString *enTypeId=@"100"; NSStri ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

How can indirect references in ksh be utilized to manipulate arrays effectively?

I am looking to create a script similar to this: #!/usr/bin/ksh93 typeset -A foo function fillItUP { typeset -A newarr newarr["this"]="bar" newarr["another"]="tut" inputarrayname=$1 nameref $inputarrayname=newarr } The expected ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

React BrowserRouter causing issues with "invalid hook calls"

Just starting out with React and I am working on setting up paths using BrowserRouter, Route, and Routes in my code. import React from "react" import "./App.css"; import { BrowserRouter as Router, Route, Routes } from 'react-router ...

Interested in generating a nested array within nodejs using javascript?

I need help creating an array of arrays using the provided record. user_permission = [ { _id: 1, description: 'chairman list', main_module: 'admin', sub_module: 'admin' }, { _id: 2, description: 'creat ...

What is the conventional method for sending data by utilizing the output of a previous data submission in Node.js with Express and FaunaDB?

I am in the process of revising a project and have a question about how to post an array of data using the return value of a previous post request as the ID. Here is an overview of the data structure: Checklist A [ChecklistItem 1, ChecklistItem 2, Checkli ...

What is the most effective method for saving pre-set items on an Android device?

When creating a list of objects belonging to the same class but with different data in their members, what would be the most effective way to load the data? The developer defines all the data, and none of it is user-input. However, it's important to h ...

Updating the geometry of vertices after rotating or moving an object

I've been experimenting with using position and rotation values to transform a mesh, but now I'd like to modify the geometry vertices directly in x, y, and z coordinates while freeing or resetting the rotation and position values. I'm not qu ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...