Home > Software engineering >  Returning object from nested object in javascript
Returning object from nested object in javascript

Time:12-30

I've an object with values

{
  "condition": "and",
  "properties": [
    {
      "dtsb-data": "Name",
      "dtsb-condition": "contains",
      "dtsb-value": "10"
    },
    {
      "condition": "or",
      "properties": [
        {
          "dtsb-data": "Name",
          "dtsb-condition": "contains",
          "dtsb-value": "20"
        },
        {
          "dtsb-data": "Name",
          "dtsb-condition": "contains",
          "dtsb-value": "30"
        }
      ]
    }
  ]
}

I want to get properties only if condition key is there

I've tried using so but failed to get output like below

   {
      "dtsb-data": "Name",
      "dtsb-condition": "contains",
      "dtsb-value": "10"
    }
    {
          "dtsb-data": "Name",
          "dtsb-condition": "contains",
          "dtsb-value": "20"
     }
     {
          "dtsb-data": "Name",
          "dtsb-condition": "contains",
          "dtsb-value": "30"
     }

My code is:

function printList({
  value,
  condition
}) {
  return [value, ...(condition ? printList(properties) : [])]
}
console.log(printList(list));

CodePudding user response:

You can use flatMap and recursion to extract these conditions as a flat array:

const flattenProperties = conditions =>
  conditions.condition ? conditions.properties.flatMap(e => 
    e.condition ? flattenProperties(e) : e
  ) : [];

const conditions = {
  "condition": "and",
  "properties": [
    {
      "dtsb-data": "Name",
      "dtsb-condition": "contains",
      "dtsb-value": "10"
    },
    {
      "condition": "or",
      "properties": [
        {
          "dtsb-data": "Name",
          "dtsb-condition": "contains",
          "dtsb-value": "20"
        },
        {
          "dtsb-data": "Name",
          "dtsb-condition": "contains",
          "dtsb-value": "30"
        }
      ]
    }
  ]
};

console.log(flattenProperties(conditions));

CodePudding user response:

It might be something like this.

const parse =
  (node) => {
    return node.condition
      ? node.properties.flatMap(parse)
      : node
  }
  • Related