object values javascript

Object Values in JavaScript

JavaScript is an object-oriented programming language, and objects are one of the fundamental data types. Objects in JavaScript are collections of key-value pairs, where each key is a string (or a symbol) and each value can be of any data type, including other objects.

Accessing Object Values

To access the values of an object in JavaScript, you can either use the dot notation or the bracket notation.


const person = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    state: "NY"
  }
};

// Dot notation
console.log(person.name); // Output: John
console.log(person.address.city); // Output: New York

// Bracket notation
console.log(person["name"]); // Output: John
console.log(person["address"]["city"]); // Output: New York

Iterating over Object Values

You can use a for...in loop to iterate over the values of an object in JavaScript.


const person = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    state: "NY"
  }
};

for (const key in person) {
  console.log(person[key]);
}
// Output: John
//         30
//         {city: "New York", state: "NY"}

Alternatively, you can use the Object.values() method to get an array of the object's values.


const person = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    state: "NY"
  }
};

const values = Object.values(person);
console.log(values); // Output: ["John", 30, {city: "New York", state: "NY"}]

Conclusion

Object values in JavaScript are the values associated with the keys in an object. You can access them using dot notation or bracket notation, and iterate over them using a for...in loop or the Object.values() method.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe