Home > Enterprise >  Node js check if element exist and return a value
Node js check if element exist and return a value

Time:09-21

  1. How to check on "info" if "Test 3" exists?
  2. And if it does return the "name" and the "Test 3" values?
const z = {
  data: {
    value: [{
      name: 'Test1',
      info: {
        'Test 1': 'Test 1',
        'Test 3': 'Testing 3',
        'Test 4': 'Testing 4',
        'Test 5': 'Testing 5'
      },
    },
    {
      name: 'Test2',
      info: {
        'Test 1': 'Test 1',
        'Test 4': 'Testing 4',
      },
    },
    {
      name: 'Test3',
      info: {
        'Test 1': 'Test 1',
        'Test 3': 'Testing 3',
        'Test 5': 'Testing 5'
      }
    }]
  }
}

I tried this to filter on the name Test for the Objects and then check if it exists and print it.

const u = z.data.value.filter(t => Object.keys(t.info).includes("Test 3"))
if (u){
    console.log(u)
}

I am trying to get the name value back into an array, if "Test 3" is part of the info section.

[
 'Test1',
 'Test3'
]

CodePudding user response:

You're almost there, you just need to add map after filter to get the final result.

const z = {
  data: {
    value: [{
      name: 'Test1',
      info: {
        'Test 1': 'Test 1',
        'Test 3': 'Testing 3',
        'Test 4': 'Testing 4',
        'Test 5': 'Testing 5'
      },
    },
    {
      name: 'Test2',
      info: {
        'Test 1': 'Test 1',
        'Test 4': 'Testing 4',
      },
    },
    {
      name: 'Test3',
      info: {
        'Test 1': 'Test 1',
        'Test 3': 'Testing 3',
        'Test 5': 'Testing 5'
      }
    }]
  }
}

const u = z.data.value.filter(t => Object.keys(t.info).includes("Test 3")).map(t => t.name)

console.log(u)

  • Related