Create a function called `keyPair` that takes in two input objects and a specified key string as parameters. The function should be designed to compare obj1 and obj2

Can someone provide guidance on writing a function keyPair(obj1, obj2, key)? The function should take two objects and a key string as parameters and return an array with the values of the specified key in both objects.

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

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

  return arr;
}

let dog1 = { name: 'Buddy', breed: 'Labrador' };
let dog2 = { name: 'Bailey', breed: 'Golden Retriever' };

console.log(keyPair(dog1, dog2, 'breed')); // [ 'Labrador', 'Golden Retriever' ]
console.log(keyPair(dog1, dog2, 'name')); // [ 'Buddy', 'Bailey ]

I've been struggling with this task, so any help would be appreciated. Thanks!

Answer №1

If you simply avoid checking for the name property and refrain from looping over every property, the function will operate as intended.

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 condensed for brevity

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 ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging numerous Text elements within a solitary Drag and Drop container with the z-index property

I am facing a challenge with stacking twelve arguments in no particular order on a drag and drop element. The texts overlap each other, making it difficult for the end user to see them clearly when dragging and dropping. Is there a way to stack texts using ...

Customize your JQuery/HTML5 Slider to accept user input

Currently, I am developing a time tracking mobile application in MVC4, which includes the use of a slider input type. <input type="range" name="time_verdi" id="slider" value="7.5" min="0.0" max="24" step="0.5" data-highlight="true"/> When using thi ...

View setup in progress

I'm interested in implementing something along these lines: app.config(function($routeProvider){ $routeProvider.when('products/list', { controller: 'ProductListCtrl', templateUrl : 'products/list/view.html', ...

Maintaining an onExit function in the ui-router framework

I am trying to implement an animation on an element within a page when the user is transitioning out of a state. Here is my current code snippet: { ....., views: { ... }, onExit: function(){ someEle.classList.remove("someClass"); // ...

Is it possible to update the page title with JQuery or JavaScript?

Is it possible to modify the page title using a tag inside the body of the document with jQuery or JavaScript? ...

incorporate setInterval() with a dynamic variable serving as the millisecond value

During initialization of the component, a value is fetched from the ngrx store and used as a configuration. this.storeService.selectMConfig().subscribe(res => { if (!res) return; const refreshValue = Number(res.items[0].value) * ...

What is the best way to access the display property of a DOM element?

<html> <style type="text/css"> a { display: none; } </style> <body> <p id="p"> a paragraph </p> <a href="http://www.google.com" id="a">google</a> &l ...

"Node.js and Webpack - the dynamic duo of

Have you ever wondered why we need to use webpack and npm to install node for JavaScript, when we can simply run JavaScript code directly in our browser? And how exactly do we go about implementing webpack into our project files? ...

Issue with base64 in Discord.js captcha channel system

Greetings everyone, and a special welcome to those willing to assist me. I am currently working on a project that involves verifying users through a hash decryption challenge system (base64). However, I've encountered an issue where the verification p ...

Which method is more efficient in OOP: invoking a function to fetch a value or directly accessing the value?

Suppose I have a class called File class File { public: File(int length); getLength(); //returns length int value int length; } When comparing the performance impact between directly accessing File.length (assuming it's ...

Communication with child processes in node.js is not done using the child_process module

Hello Everyone, I'm currently experimenting with node.js to utilize JS plugins developed by others using the child_process API. However, I'm facing an issue where the child process is not able to communicate effectively with the parent process. ...

PHP - array_push function

Here's a function that I have: function push_to_array() { $array_of_data = func_get_arg(0); for($i = 1; $i < func_num_args(); ++$i){ $array_of_data[] = func_get_arg($i); } return $array_of_data; } You can use it with an e ...

"Connecting a checkbox and radio button to a button for page navigation using JavaScript - a step-by-step guide

How can I link a checkbox and a radio button with a button to open a page using JavaScript? For instance: Select a checkbox and a radio button, then click a button to open a page. This concept caters to everyone: Select a checkbox and a radio button, then ...

PHP - Implementing a Submit Button and Modal Pop-up AJAX across multiple browsers in PHP

As a newbie in PHP AJAX coding, I'm facing a challenge with having two browsers. My goal is to click the submit button on one browser and have a modal popup on the other browser simultaneously. Essentially creating a chat system where only a button an ...

How can we determine the remaining balance in the user's wallet after making purchases using JavaScript?

There are three arrays containing data from the back-end, with unknown names or products. The task is to calculate the total amount spent by the user and how much money is left in their wallet. In case the user runs out of money, they can take a loan which ...

Find all elements within JSON data using lodash.js

Hello friends, I'm dealing with a JSON object: var companies = [ { id: 1, name: "Test Company", admin: "Test Admin" }, { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' }, { id: 3, name: "New Company", ad ...

Determine the frequency of a particular value within a PHP array

I am attempting to determine the number of products within a specific category. I have nested the table of products inside the table of categories and tried using array count values but I am encountering difficulties. Here is the current code snippet: ...

obtaining values from a JSON object and JSON array in java

I am struggling to generate a JSON string that combines both a JSON object and a JSON array. Here is the desired format: { "scode" : "62573000", "sname" : "Burn of right", "icd10" = [ {"icode" : "T25.229?", "iname" : "Right foot"}, {"icode" ...

Surprising message found within a pug file containing javascript code

I'm encountering an issue that I am unsure how to resolve. I am relatively new to working with pug files and the error message below is appearing: Error: /home/nobin/jadeApp/views/show_message.pug:9:33 7| else 8| h3 New person, ...

Tips for creating dynamic alerts using mui v5 Snackbar

My goal is to call an API and perform several actions. After each action, I want to display the response in a Snackbar or alert. Despite iterating through the messages in a map, I'm only able to show the first response and none of the others. Here is ...