How to Create a Single Object from Multiple Variable Using Shared Key Names and Values in JavaScript

How to Create a Single Object from Multiple Variable Using Shared Key Names and Values in JavaScript

What if you want to know how to create a single object from multiple variables using shared names and values in JavaScript? Sometimes, it's helpful to group separate stored values together as on object – like if you're modeling people, places, or things from the real world. As usual with code, there's more than one way to get the job done. Let's take a look at how to combine variables to create an object using shared names and values in JavaScript.

Parameters, and Expected Results

The parameters of this code challenge are:

  • Starting with multiple variables
  • Variable names are known
  • Using a JavaScript arrow function to merge and objectify

The expected result is that:

  • Multiple variables are combined into a single object
  • Object keys and variable names are the same
  • Object values and variable values are the same

Programmatic Approach

Programmatically, it's simple enough to write the process out in long-form declarations:

const create_dog = (name, age, breed, gender) => {

	return {
		name: name,
		age: age,
		breed: breed,
		gender: gender
	};
	
}

The above code works just fine. First, it accepts four separate variables (name, age, breed, and gender). Then it creates a new object – using the variable names as the object's key names and the variable's values as the object's values. It creates and returns a single object with shared key names and variable values from multiple input variables.

But, there's actually a simpler way of doing this.

A Simplified Solution

It's one thing to write code that works, but it's another to write optimized code that works efficiently.

Take a look at this single line approach that accomplishes the same results as the previous code.

const create_dog = (name, age, breed, gender) => ( { name, age, breed, gender } );

Pretty cool, right?

Using this single line arrow-function style declaration, JavaScript knows to use the right key names and values to create and return the same object. And, it uses less code – which results in faster execution times. Run time is not a huge deal in this small example, but if you were dealing with large datasets and lots and lots of dogs then anything you can do to optimize how your code runs can be a large improvement – every optimization counts, as overall optimization is a lump-sum game.

Testing the Results

You can test the results using console.log()

const create_dog = (name, age, breed, gender) => ( { name, age, breed, gender } );

console.log( create_dog("Jack", 8, "Golden Retriever", "male") );

/*

Returns:

{
	name: Jack,
	age: 8,
	breed: Golden Retriever,
	gender: male
}

*/