简体   繁体   中英

Node js check if element exist and return a value

  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'
]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM