Examples

Examples · Objects

JavaScript Object Examples

A runnable cookbook of everyday object tasks — clone, merge, get keys and values, iterate, check a property, rename a key, count and invert — each a short snippet you can run.

XCODXExamples · Updated

Overview

Short, copy-paste examples for the most common things you do with objects in JavaScript. Every snippet runs — edit any of them in the online JavaScript compiler. For the mechanics behind a method, follow the links to its reference page.

Examples

Clone (shallow copy) an object

const user = { name: 'Ada', age: 36 };
const copy = { ...user };
copy.age = 40;
console.log(user.age); // 36 — original untouched

Merge two objects

const defaults = { theme: 'light', size: 'md' };
const prefs = { theme: 'dark' };
console.log({ ...defaults, ...prefs }); // { theme: 'dark', size: 'md' }

Get the keys

console.log(Object.keys({ a: 1, b: 2, c: 3 })); // ['a', 'b', 'c']

Get the values

console.log(Object.values({ a: 1, b: 2, c: 3 })); // [1, 2, 3]

Get key-value entries

console.log(Object.entries({ a: 1, b: 2 })); // [['a', 1], ['b', 2]]

Iterate over an object

Check if a property exists

const user = { name: 'Ada' };
console.log(Object.hasOwn(user, 'name')); // true
console.log('email' in user);             // false

Rename a key

const { name: fullName, ...rest } = { name: 'Ada', age: 36 };
const renamed = { fullName, ...rest };
console.log(renamed); // { fullName: 'Ada', age: 36 }

Count the properties

console.log(Object.keys({ a: 1, b: 2, c: 3 }).length); // 3

Invert keys and values

const codes = { ok: 200, notFound: 404 };
const byCode = Object.fromEntries(
  Object.entries(codes).map(([k, v]) => [v, k])
);
console.log(byCode); // { '200': 'ok', '404': 'notFound' }

Frequently asked questions

How do I copy an object in JavaScript?
For a shallow copy use spread: { ...obj }. For a deep copy of plain data use structuredClone(obj).
How do I merge two objects?
Spread them into a new object: { ...a, ...b }. On a key conflict, the rightmost object wins.
How do I loop over an object?
Use for (const [key, value] of Object.entries(obj)), or iterate Object.keys(obj) when you only need the keys.