首页 > 解决方案 > How do I query a Key-Value object in Java

问题描述

If I have an array of strings, how do I query all VALUES in a key-value object with my listOfStrings, and return the related KEYS??

"listOfStrings": ["4444", "5555"]

"secretCodes": [
{
"secret": "John",
"value": "4444"
},
{
"secret": "Paul",
"value": "0001"
},
{
"secret": "George",
"value": "0002"
},
{
"secret": "Ringo",
"value": "5555"
},
{
"secret": "Pete",
"value": "0008"
}
]

标签: javascriptarraysjsonlist

解决方案


If you want to return the secret names that correspond to the values in the codes array you could do this:

let secretCodes = [
  { secret: "John", value: "4444" },
  { secret: "Paul", value: "0001" },
  { secret: "George", value: "0002" },
  { secret: "Ringo", value: "5555" },
  { secret: "Pete", value: "0008" },
];

function getSecretName(codes) {
  let matchingValues = secretCodes.filter(obj => codes.includes(obj.value));
  return matchingValues.map(value => value.secret);
}

console.log(getSecretName(["4444", "5555"]));

// returns ["John", "Ringo"]


推荐阅读