-2

In NodeJS,JavaScript, I have a JSON that looks like this:

console.log(object1.Tags)

[
  { Key: 'branch', Value: 'master' },
  { Key: 'env', Value: 'staging' },
  { Key: 'Name', Value: 'host-number-137' },
  {
    Key: 'DNSalt',
    Value: 'name.of.dns'
  },
  { Key: 'env_role', Value: 'dev' },
  { Key: 'role', Value: 'app' },
  { Key: 'userId', Value: 'U123456789' }
]

I'm trying to get the value of the key that holds DNSalt but I can't seem to do it.

In NodeJS/JavaScript, is it possible to get the value of the key called "DNSalt" (AKA name.of.dns)?

Thanks ahead!

jessefournier
  • 181
  • 1
  • 2
  • 13
  • You can iterate through the array and search for the object containing the correct `key`. Once you find it, then you can read the value. – Tomasz Staszkiewicz Sep 14 '22 at 11:54
  • [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) – kiranvj Sep 14 '22 at 11:57

1 Answers1

1

An idea can be to use array.find that take a condition and return first element that match the condition

var data = [
  { Key: 'branch', Value: 'master' },
  { Key: 'env', Value: 'staging' },
  { Key: 'Name', Value: 'host-number-137' },
  {
    Key: 'DNSalt',
    Value: 'name.of.dns'
  },
  { Key: 'env_role', Value: 'dev' },
  { Key: 'role', Value: 'app' },
  { Key: 'userId', Value: 'U123456789' }
];

const res = data.find(obj => obj.Key === 'DNSalt');
console.log(res.Value);
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35