Home > database >  How to match the string in JSON object and bring the value from array?
How to match the string in JSON object and bring the value from array?

Time:10-20

Below is the array of key/value pairs. I want to match the key from below array and bring its value. But my string is "[email protected]" and loop through below array and bring its value.

[{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}]

I want access above array and bring value.

CodePudding user response:

We traverse on the given array and then the second for loop is just to get the key of each element. But if each objects contains only one key pair then the second for loop will always run only once. Making the overall time complexity of O(N).

let a = [{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}]
let s = "[email protected]"

for(let i = 0; i<a.length; i  ){
    for (var key in a[i]) {
        if (key === s){
            console.log(a[i][key])
        }
    }
}

CodePudding user response:

let json = '[{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}]'
let o = JSON.parse(json) // Create an object from the JSON
o.forEach(function(obj) { // Loop through each object
    for (const key in obj) { // Loop through the keys in the object you are up to
        if (key == '[email protected]') { // If it's the key you want...
            console.log(obj[key]) // ...get the value
        }
    }
})

Also see https://stackoverflow.com/a/8430501/378779

CodePudding user response:

We can just loop through the array and check if the desired key exist in any of the key:value pairs.

let data = [{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}];
let res = '';

for ( const item of data ) {
    if ( '[email protected]' in item ) {
        res = item['[email protected]'];
        break;
    }
}

console.log(res);

CodePudding user response:

try this

var arr = [{"[email protected]":"custom"}, {"[email protected]":"free"}, {"[email protected]":"free"}];
const searchKey = "[email protected]";
var res = null;

for (item of arr) {
  if (searchKey in item ) {
    res = item[searchKey];
    break;
  }
}

console.log(res);
  • Related