Stack Exchange
How to fetch matching key values from JSON object?
I have an object with the following data:
obj =
{
  key: 'mykey1597855209',
  integrity: 'sha512-T9JW=='
}
{
  key: 'mykey159785520915978552101597855212',
  integrity: 'sha512-T9JWj=='
}
{
  key: 'mykey15978552091597855210',
  integrity: 'sha512-lcddfd=='
}
{
  key: 'otherkey15978552091597855210',
  integrity: 'sha512-abcdfd=='
}

When I do console.log(typeof obj) , I get object as output
I want to store only unique integrity values in an array for the keys which have mykey* in the key value

Desired Output:

[ 'sha512-T9JWj==', 'sha512-lcddfd==' ]


Code:

var output = [];

for (var key in obj) {
  if(obj[key] === 'mykey') {
    output.push(obj[integrity])
  }
}

console.log(output.join(', '))


you can use regex to match with pattern rather than ===.

okay. also how to get only unique integrity value?

for unique integrity, create a dictionary. Here dictionary key will be integrity.
const dict = { }
for(var key in obj) {
dict[key[integrity]] =  key
}

You mention in a comment on an answer that obj is not an array. You are correct. It is not an array. Nor is it "JSON" or a "JSON Object" (JSON always has been and always will be a string). obj is a syntax error.

You first filter the array to obtain only objects with a matching key value, map each resulting element to its integrity property, create a Set from that array, and finally use spread syntax to obtain the result as an array.


const arr = [
{
  key: 'mykey1597855209',
  integrity: 'sha512-T9JWj=='
},
{
  key: 'mykey159785520915978552101597855212',
  integrity: 'sha512-T9JWj=='
},
{
  key: 'mykey15978552091597855210',
  integrity: 'sha512-lcddfd=='
},
{
  key: 'otherkey15978552091597855210',
  integrity: 'sha512-abcdfd=='
}];
const res = [...new Set(arr.filter(({key})=>/mykey/.test(key)).map(({integrity})=>integrity))];
console.log(res);




please note that obj is not an array

Please provide some valid sample data then.
