Home > Software engineering >  How to extract values from an object and return it in an array of strings with specific requirements
How to extract values from an object and return it in an array of strings with specific requirements

Time:09-08

I'm trying to build a function that will extract the values from an object and creates an array of strings.

In the snippet below, you can see an example of what I did until now but that is not fully correct to my requirements.

Let's say I have data as in the example

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

Right now I'm getting an array of strings for every single value in fact the result if you run it is

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

But what I need is the following array based if we have or not a nested object inside the data


[
  * 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 is ok as no nested objects
  "true",
  "true",
  "true",
  "true"
]

The above result is what I'm searching

Another example as this below data

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

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

My issue at the moment is how to get into the expected results plus needs to be a - between the aggregated results.

We can also have a situation where data looks like this

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

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

The snippets abut my first 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

The nested objects will never go more deeply as per following example

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

Expected result as

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

CodePudding user response:

The OP already came up with a recursive approach.

In order to achieve the OP's expected result(s), one has to implement the recursively operating function in a way that it will concatenate any array-type's item and any of an object-type's value, regardless of the (currently processed) data-structure's nesting level.

And for the not to be concatenated first level entries of the OP's data object one just needs to map the very object's values by said 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; }

  • Related