Javascript Objects

The basics

The basics of a javascript object

// basic object 
const obj = {
  key: val
}

// nested obj and arrays
const product = {
  id: "858fc585-0d23-4f55-b766-8c133d2922c7",
  name: "Stileto high heels",
  specificaions: {
    colour: "red",
    type: "shoe"
  },
  locations: [
    { id: 1, name: "Oxford Street", qty: 23 },
    { id: 2, name: "Regent Street", qty: 9 }
  ]
}

// with named keys. daft, but seems all the rage in go and python
const colours = {
  red: { main: "red", subs: ["rogue","ruby"] },
  blue: { main: "blue", subs: ["cyan","azure"] },
}

Add another key value to a javascript object

// start object
const obj = {
  name: "John",
  gender: "male"
}

obj['age'] = 54;

// new object will look like 
{
  name: "John",
  gender: "male",
  age: 54
}

Update and delete values in a javascript object

const obj = {
  name: "John",
  gender: "male",
  age: 54,
  address: {
    street: "9 Infinite Loop",
    country: "US" 
  },
  contactDetails: [
    { type: "tel", value: "555-6666-6666" },
    { type: "instagram": "raynoppe" }
  ],
  active: true,
}

// method 1 meh
obj["age"] = 23;

// method 2
obj.age = 21;
obj.active = false;

// change the value of a nested object
obj.address.street = "1 Hyde Park";

// change the first value in a nested array
obj.contactDetails[0].value = "111-2222-3333";

// clearing a value
obj.gender = "";
obj.address.street = "";

// you can also null the value
obj.gender = null;
obj.address.street = null;

// delete a key pair from an array
delete obj.gender; // don't risk being non woke
delete obj["gender"];

Check to see if a javascript object is empty

const obj = {}

// my go to way
if (!Object.keys(obj).length) {
  // object is empty
}
if (Object.keys(obj).length) {
  // object is not empty
}

// old skool
if (Object.keys(obj).length === 0) {
  // object is empty
}

Check to see if a key exist in a javascript object

const obj = {
  name: "Susan",
  gender: "female"
  age: 19
}

// my go to method as it check it's own properies and properties inherited from the prototype chain
if ('key' in obj) {
  console.log('Key exists');
} else {
  console.log('Key does not exist');
}

// if you only want to check if a key only exist in its own properties
if (obj.hasOwnProperty('key')) {
  console.log('Key exists');
} else {
  console.log('Key does not exist');
}
// or ES13 method
if (Object.hasOwn(obj, 'key')) {
  console.log('Key exists');
} else {
  console.log('Key does not exist');
}

Check to see if a value exist in a javascript object

const obj = {
  name: "Abdul",
  position: "Manager",
  department: "Sales"
}

// if you know the key you want to check the value for
if (obj.name === "Abdul") {
  // exists
} 

// if you want to check alll the key for a value
// convert to array method
function hasValue(obj, value) {
  return Object.values(obj).includes(value);
}
if (hasValue(obj, "Manager")) { console.log("true") }
// shorthand
let isManager = hasValue(obj, "Manager") ? true : false;
console.log("isManager", isManager);

// using the some method against an array
const checkIfExists = (obj, value) => {
	return Object.entries(obj).some(([key, val]) => val === value);
}
console.log(checkIfExists(obj, "Manager")); // Output: true

// a for loop and let you do some logic if found
for (let key in obj) {
  if (obj.hasOwnProperty(key) && obj[key] === value) {
    // do some fancy logic here
  }
}

Loop a javascript object

Yes, you will have to loop an object because there is often that backend python/go developer that uses an object like and array.

const obj = {
  1: { label: "Enter name", type: "text" },
  2: { label: "Enter email", type: "email" },
}

// my go to as I get a clean key and value back
Object.entries(obj).forEach(([key, value]) => {
  console.log(key + ': ' + value.label);
});
/* Output:
1: Enter name
2: Enter email
*/

// option 2 old school
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}

// if you just want to loop of an object and get the keys
Object.keys(obj).forEach(key => {
  console.log(key + ': ' + obj[key]);
});

// option 2 old school
for (let key of Object.keys(obj)) {
  console.log(key + ': ' + obj[key]);
}

Copy a javascript object

There is a quick way and a in depth way. Be careful when using the quick way as it doesn’t do a deep copy and in some frameworks it will copy all the framework added junk.

const obj = {
  name: "John",
  gender: "male"
}

// quick way
const newObj = {...obj};

// my prefered way
const newObj = JSON.parse(JSON.stringify(obj));
Scroll to Top