Guide to retrieving data from an object and organizing it into an array of strings based on certain criteria

I'm currently working on a function to extract values from an object and generate an array of strings.

In the snippet below, I have provided an example of my progress so far, but it does not completely meet my requirements.

For instance, consider the data in this example:

const data = {
      age: {
        min: '17',
        max: '66'
      },
      gender: ['male', 'female'],
      rosacea: 'true',
      rosacea_papulo_pustulosa: 'true',
      severe_rosacea: 'true',
      nurse_contact: 'true',
    };

Currently, the output is an array of individual strings for each value, as shown:

[
  "17",
  "66",
  "male",
  "female",
  "true",
  "true",
  "true",
  "true"
]

However, what I need is an array that considers nested objects within the data. The desired output should be:


[
  * This is the result of age min: '17' and max: '66'
  "17 - 66",
  * This is the result of gender male and female
  "male - female",
  * The rest remains the same without nested objects
  "true",
  "true",
  "true",
  "true"
]

The above output is what I am aiming for.

Here is another example with the following data:

{disease":{"valid":["MDD","PTSD"],"invalid":["None"]}}

// expected result
[
 "MDD - PTSD",
 "None"
]

My challenge at the moment is achieving the expected results while adding a - between the aggregated values.

We might encounter scenarios like the one shown below:

{ageGroup: ["1","2","3", ..., "n"]}

// expected result
[
 "1 - 2 - 3 ... etc ..."
]

The following code shows my initial attempt:

const data = {
  age: {
    min: '17',
    max: '66'
  },
  gender: ['male', 'female'],
  rosacea: 'true',
  rosacea_papulo_pustulosa: 'true',
  severe_rosacea: 'true',
  nurse_contact: 'true',
};

const getValues = (data, values = []) => {
  if (typeof data !== 'object') {
    return [...values, data];
  }
  return Object.values(data).flatMap((v) => getValues(v, values));
};

console.log(getValues(data))

Update

Nested objects will not go deeper than the following example:

age: {
  group1: {
    min: '1',
    max: '6'
  }
  group2: {
    min: '7',
    max: '10'
  }    
  },

Expected result:

[
'1 - 6',
'7 - 10'
]

Answer №1

The initial poster has already devised a recursive solution.

To meet the expected results of the original poster, one must implement a recursive function that will concatenate any item in an array and any value in an object, regardless of the current nesting level of the data structure being processed.

For the top-level entries of the original poster's data object that should not be concatenated, one simply needs to map the object's values using the aforementioned recursive function.

function stringifyDataRecursively(data) {
  let result = '';

  if (data && (typeof data === 'object')) {
    if (Array.isArray(data)) {

      result = data
        .map(stringifyDataRecursively)
        .join(' - ');

    } else {

      result = Object
        .values(data)
        .map(stringifyDataRecursively)
        .join(' - ');
    }
  } else {

    result = data;
  }
  return result;
}

const sampleData = {
  age: {
    min: '17',
    max: '66'
  },
  gender: ['male', 'female'],
  rosacea: 'true',
  rosacea_papulo_pustulosa: 'true',
  severe_rosacea: 'true',
  nurse_contact: 'true',
};
console.log(
  'stringified `sampleData` ...',
  Object
    .values(sampleData)
    .map(stringifyDataRecursively)
);

const sampleData_2 = {
  disease: {
    valid: ['MDD', 'PTSD'],
    invalid: ['None'],
  },
};
console.log(
  'stringified `sampleData_2` ...',
  Object
    .values(sampleData_2)
    .map(stringifyDataRecursively)
);
console.log(
  'stringified `sampleData_2.disease` ...',
  Object
    .values(sampleData_2.disease)
    .map(stringifyDataRecursively)
);

const sampleData_3 = {
  group1: {
    min: '1',
    max: '6',
  },
  group2: {
    min: '7',
    max: '10',
  }, 
};
console.log(
  'stringified `sampleData_3` ...',
  Object
    .values(sampleData_3)
    .map(stringifyDataRecursively)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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

Obtaining access to an element using jQuery AJAX in MVC

When using jQuery ajax to send data to an action, I want to display the returned data in a table. The action method returns an object in Json format: public JsonResult CountryList(.....) { CountryTypeViewModel obj = new CountryTypeViewModel(); . ...

Using Node.js for HTML redirections involves creating routes and setting

I am currently attempting to connect my Node.js API with my HTML pages. For the most part, everything is functioning correctly, but I have encountered some confusion along the way. Is there a more efficient method for redirecting an HTML page? Typically, ...

Tips for enabling TypeScript's static typings to function during runtime

function multiply(num: number): number { console.log(num * 10) // NaN return num * 10 } multiply("not-a-number") // result == NaN When attempting to call the function above with a hardcoded invalid argument type, TypeScript correctly identifies and w ...

Utilize JavaScript to import an XML file from a specific directory

I am trying to use JavaScript to load an XML file. Below is the code I am using to load the XML file when it is in the same folder: if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHtt ...

What steps can I take to address security issues related to iframes?

Are there other security risks to consider when using iframes besides XSS vulnerabilities? How can I ensure that my website is secure when utilizing iframes? I've seen some JavaScript code that uses top.window, but I'm hesitant to rely on client ...

Error: React/Express - The renderToString() function encountered an unexpected token '<'

As I work on implementing server-side rendering for my React/Express application, I have hit a snag due to a syntax error related to the use of the react-dom/server renderToString() method. In my approach, I am following a tutorial mentioned here - The sn ...

How can JavaScript/jQuery be used to update LocalStorage Objects when editing a form?

Having trouble pinpointing an issue with my code. Despite making modifications, the values in localStorage are not updating as expected. Any suggestions on what may be causing this problem? Note: Changing const idx to const i resulted in only the final va ...

What can you do with arrays and the improved for loop syntax?

Could someone please provide an explanation of what is happening in this method? class test{ public static void main(String args[]) { int[] x = new int[4]; int[] xy = new int[4]; for(int j : x) { xy[j] += ...

Is there a way to incorporate icons into the rows of a react ag-grid?

I'm currently using the react ag-grid library and I've attempted to use the cellRenderer function, but unfortunately, it's not working as expected. columnDefinationWaterUsage: [ { headerName: "", cellRenderer: count ...

AngularJS Perspectives: Unveiling the Secrets of Successful Implementation

Do you have any tips on troubleshooting AngularJS views? I found a demo at AngularJS: ngView, but the provided jsfiddle doesn't seem to work. I've been trying to play around with it, but still haven't had any success. This is the code I&apo ...

Adjust the placement of an HTML component using Angular 2

My angular component template includes: <my-app> <nav id="nav-bar"> <ul> <li id="item-1"></li> <li> <div id="item-2"></div> </li> <li id="item-3"></li> ...

What steps should I take to arrange this information in this particular format?

Exploring nested comments data and structuring it effectively. I am seeking assistance in optimizing a function that can transform an array into a structured format, as depicted below. raw data const data = [ { id: 1, text : "Hell ...

Avoiding the need to use brackets inside driver.execute_script

I am facing the issue where Webdriver is unable to locate an element, so I want to create a general solution for this: def check_element(driver, xpath): checked = driver.execute_script( """function getElementByXpath(path) {{return docume ...

Disable infinite scrolling when a checkbox is clicked

Currently, I have implemented infinite scrolling on a table and it is functioning properly. <tbody infinite-scroll-disabled="myModule.isScrollingDisabled()" infinite-scroll="myModule.nextPage()" infinate-scroll-immediate-check="false" infinite-scroll-d ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

Is it possible to organize MongoDB records that possess identical update timestamps?

My goal is to validate a route within my Express server using Supertest. This particular route retrieves data from a MongoDB, and the data is then sorted based on the updatedAt field. While attempting to test the order of the output, I encountered an issu ...

Random access list operations in C++ are highly efficient and optimized

Similar Question: How to retrieve a specific element from a list based on its position? With Python, you can access elements within a list using random access methods.... list = [1,12,3] print(list[1]) Running this code will display the value 12... ...

Incorporating a dynamic variable into HTML using a separate C# class

In my ASP.NET framework, I am looking to personalize the paragraph text on the welcome page for users after they log in. Currently, the code has the following paragraph: <p> Welcome to the website! </p> What I want is to include their logi ...

Keeping API Credentials secure and easily editable during runtime - is that possible?

Currently, I am actively engaged in a node project where my application interacts with another application's API to retrieve or upload data. To ensure authentication by the external server, every request needs to have a specific key. As of now, I stor ...

Angular deep nested router interface

How can I set up nested views in Angular for the following routes? /#/app/dashboard /#/app/product/ /#/app/product/new Here is my current route configuration: $stateProvider .state('app',{ url: '/app', templateUrl ...