Write a function keyPair(obj1, obj2, key) that accepts two objects and a key string as arguments. bj1 and obj2 [closed]

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Write a function keyPair(obj1, obj2, key) that accepts two objects and a key string as arguments. bj1 and obj2 [closed] on this date .

Write a function key Pair(obj1, obj2, key) that accepts two objects and a key string as arguments.
The function should return an array containing the values of the given key in obj1 and obj2.

function keyPair(obj1, obj2, key) {
  let arr = [];

  for (let key in obj1) {
    if (key === 'name') {
      arr.push(obj1[key]);
      arr.push(obj2[key]);
    }
  }

  return arr;
}

let cat1 = { name: 'jinkee', breed: 'calico' };
let cat2 = { name: 'garfield', breed: 'red tabby' };

console.log(keyPair(cat1, cat2, 'breed')); // [ 'calico', 'red tabby' ]
console.log(keyPair(cat1, cat2, 'name')); // [ 'jinkee', 'garfield ]

someone should give me a little guide have been struggling with it. Thanks

Answer

All you needed to do was not check for the property being name and not loop over every property and it works exactly as expected

function keyPair (obj1, obj2, key) {
      let arr = [];
  
      arr.push(obj1[key]);
      arr.push(obj2[key]);
  
      return arr;
  }

  
  let cat1 = { name: 'jinkee', breed: 'calico' };
  let cat2 = { name: 'garfield', breed: 'red tabby' };
  console.log(keyPair(cat1, cat2, 'breed')); // [ 'calico', 'red tabby' ]
  console.log(keyPair(cat1, cat2, 'name')); // [ 'jinkee', 'garfield ]

The code can also be significantly shortened

const keyPair = (obj1, obj2, key) => [obj1[key], obj2[key]]

  
  let cat1 = { name: 'jinkee', breed: 'calico' };
  let cat2 = { name: 'garfield', breed: 'red tabby' };
  console.log(keyPair(cat1, cat2, 'breed')); // [ 'calico', 'red tabby' ]
  console.log(keyPair(cat1, cat2, 'name')); // [ 'jinkee', 'garfield ]