• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Assign keys to an object with the same name

Assign keys to an object with the same name

Assign keys to an object with the same name

When you are assigning keys to an object, if the key is the same name as the variable that holds the value you want to assign you can omit the value assignment altogether. This prevents you from having to repeat yourself, something we all hate doing. Let’s take a look at an example using some of the same data from our last example:

let name = 'bob';
let age = 34;
let job = 'carpenter';

// instead of this
let myObject1 = { name: name, age: age, job: job };

// do this
let myObject2 = { name, age, job };

console.log(myObject2);
--> { name: 'bob', age: 34, job: 'carpenter' }

Source

https://levelup.gitconnected.com/6-javascript-code-snippets-for-solving-common-problems-33deb6cacef3

Miscellaneous

Related Snippets:

  • Deep clone a value in Node.js
  • Convert a string to an array of characters
  • Replace a portion of a string with something else
  • Check if an Item Exists in an Array

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers