Debug School

rakesh kumar
rakesh kumar

Posted on

object value and entries in javascript

In JavaScript, an object is a collection of key-value pairs where the keys are unique strings (or symbols) that act as identifiers for the corresponding values. The values can be of any type, including strings, numbers, booleans, arrays, other objects, and even functions.

Object.values() and Object.entries() are two built-in methods in JavaScript that allow you to extract the values and key-value pairs from an object, respectively.

Here's an example that demonstrates the use of these methods:

const myObj = {
  name: "John",
  age: 30,
  isMarried: true,
  hobbies: ["reading", "swimming"]
};

// using Object.values()
const objValues = Object.values(myObj);
console.log(objValues); // ["John", 30, true, ["reading", "swimming"]]

// using Object.entries()
const objEntries = Object.entries(myObj);
console.log(objEntries);
/* [
     ["name", "John"],
     ["age", 30],
     ["isMarried", true],
     ["hobbies", ["reading", "swimming"]]
   ]
*/

Enter fullscreen mode Exit fullscreen mode

As you can see, Object.values() returns an array of the values in the object, in the order they were defined in the object. In our example, the values are "John", 30, true, and ["reading", "swimming"].

On the other hand, Object.entries() returns an array of arrays, each of which contains two elements: the key and the corresponding value. In our example, the key-value pairs are ["name", "John"], ["age", 30], ["isMarried", true], and ["hobbies", ["reading", "swimming"]].

Note that the order of the key-value pairs returned by Object.entries() is not guaranteed to be the same as the order in which they were defined in the object.

You can use these methods to iterate over the values or key-value pairs of an object, or to perform various operations on them.

Image description

Image description

Image description

PRACTICAL EXAMPLE

Image description

OUTPUT

Image description

=================

Image description

OUTPUT
Image description

==============================

Image description

OUTPUT
Image description

Top comments (0)