0

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 "ss@d.com" and loop through below array and bring its value.

[{"nn@g.com":"custom"}, {"ss@d.com":"free"}, {"p23@gmail.com":"free"}]

I want access above array and bring value.

kmoser
  • 8,780
  • 3
  • 24
  • 40
  • can we traverse the array each time? What I mean to say is can we do it in O(N)? – Harsh Gupta Oct 19 '22 at 17:51
  • loop through array once and match the string – Pralayasimha Yedida Oct 19 '22 at 17:52
  • Does this answer your question? [get keys of json-object in JavaScript](https://stackoverflow.com/questions/8430336/get-keys-of-json-object-in-javascript) – kmoser Oct 19 '22 at 17:58
  • Will the keys in the array always be unique? Can you modify the array? If unique and you can modify, I'd try to start with an Object. If they won't be unique, how do you determine which to use? – mykaf Oct 19 '22 at 18:17

4 Answers4

0

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 = [{"nn@g.com":"custom"}, {"ss@d.com":"free"}, {"p23@gmail.com":"free"}]
let s = "ss@d.com"

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

Harsh Gupta
  • 527
  • 1
  • 3
  • 13
0

let json = '[{"nn@g.com":"custom"}, {"ss@d.com":"free"}, {"p23@gmail.com":"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 == 'ss@d.com') { // If it's the key you want...
            console.log(obj[key]) // ...get the value
        }
    }
})

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

kmoser
  • 8,780
  • 3
  • 24
  • 40
0

try this

var arr = [{"nn@g.com":"custom"}, {"ss@d.com":"free"}, {"p23@gmail.com":"free"}];
const searchKey = "ss@d.com";
var res = null;

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

console.log(res);
Serge
  • 40,935
  • 4
  • 18
  • 45
0

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

let data = [{"nn@g.com":"custom"}, {"ss@d.com":"free"}, {"p23@gmail.com":"free"}];
let res = '';

for ( const item of data ) {
    if ( 'ss@d.com' in item ) {
        res = item['ss@d.com'];
        break;
    }
}

console.log(res);
Jay
  • 1
  • 1