0

I am writing a function that takes an object and an array. I loop through the array and use the value as a key to look in the object.

I would like the loop to stop as soon as 1 value has been found and return that value. Somehow i keep getting undefined when running this function.

const searchInObject = function(obj, keys) {
  //if array => loop and return the first value that is found.
  //if not array and type is string find in object
  // if no array or undefined return default value
  if (Array.isArray(keys)) {
    keys.map(key => {
      if (obj[key]) return obj[key];
    })
  }
};


const obj = {
  a: '1',
  b: '2'
};
console.log(searchInObject(obj, ['a', 'b']));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • You are not returning anything from the function. Also, what is the expected output? An array of values or a subset of the object? *"return the first value that is found"* is confusing – adiga Aug 14 '19 at 14:25
  • 1
    `return keys.map...`?? – Jaydip Jadhav Aug 14 '19 at 14:26
  • I made a snippet. I changed from util. because the function is not part of any util object – mplungjan Aug 14 '19 at 14:26
  • Returns both values still, i wish to return the first that is found. @JaydipJadhav – Kevin.a Aug 14 '19 at 14:27
  • @adiga Basically i want to return one value only. That value is the first key in the loop that can be also found in the object. In this case its ' a ' – Kevin.a Aug 14 '19 at 14:29

5 Answers5

3

Just loop through the keys and check if the key exists in obj. If it does, return the value

const searchInObject = function(obj, keys) {
  if (!Array.isArray(keys))
    return;

  for (const key of keys) {
    if (key in obj)
      return obj[key]
  }
};

const obj = { a: '1', b: '2' };

console.log(searchInObject(obj, ['a', 'b']));
adiga
  • 34,372
  • 9
  • 61
  • 83
1

Try this:

const searchInObject = function(obj, keys) {
  if (Array.isArray(keys)) { //if array => loop and return the first value that is found.
    for(let i = 0; i < keys.length; i++){
      if (obj[keys[i]]) return obj[keys[i]];
    }
  } else if (typeof keys === 'string') { //if not array and type is string find in object
    return obj[keys];
  } else { // if no array or undefined return default value
    return "default value"; // change this to the default value you want
  }
};


const obj = {
  a: '1',
  b: '2'
};
console.log(searchInObject(obj, ['a', 'b']));
Mendy
  • 7,612
  • 5
  • 28
  • 42
1

You can use the Array.find() function instead. This returns the first found value or undefined if nothing is found.

const searchInObject = (obj, keys) => {
    if (Array.isArray(keys))
        return keys.find(key => obj.hasOwnProperty(key))
    else return undefined;
}

console.log(searchInObject({a: '1', b: '2'}, ['a','b']))
tripathiakshit
  • 624
  • 5
  • 17
1

I guess you want to use filter instead of map.

Below is the code:

const searchInObject = function(obj, keys) { 
    if(keys instanceof Array) { 
        keys = keys.filter(key => { 
            // This will return undefined if key is not present in object
            return obj[key];
        });
        // The filtered keys array will contain only existing keys
        // If length of keys is non zero then just return the value with first key 
        // Else return -1 or any other value
        return keys.length > 0 ? obj[keys[0]] : -1;
    }
    // If keys is not an array, return -1 (or anything else if you want to)
    return -1;
}; 

The above code will still loop through the entire keys array even if it finds the first key in obj. To optimize it, instead of using map or filter, you can just iterate over keys and return the first existing value.

Here's the code:

const searchInObject = function(obj, keys) { 
    if(keys instanceof Array) { 
        for(let key of keys) {
            if(obj[key])
                return obj[key];
        }
    }
    // If keys is not an array, return -1 (or anything else if you want to)
    return -1;
}; 
sanketd617
  • 809
  • 5
  • 16
0

Practically it not possible using the Map function to break its iteration. better way you try to use for loop or try something like below.

return keys.map(key => {
      if (obj[key]) return obj[key];
    })[0]
Jaydip Jadhav
  • 12,179
  • 6
  • 24
  • 40
  • 1
    If keys is `["c", "a"]`, this will return undefined. This is same as `return obj[keys[0]]` – adiga Aug 14 '19 at 14:33