Javascript list object values

How to iterate over object keys and values in JavaScript

There are 4 ways to iterate over an object keys and values in JavaScript:

  1. The for. in loop is used for iterating over keys of objects, arrays, and strings.
  2. The Object.keys() method returns an array of object keys.
  3. The Object.values() method returns the values of all properties in the object as an array.
  4. The Object.entries() method returns an array of the object’s key-value pairs.

The Object.keys() method was added in ES6, whereas, Object.entries() and Object.values() methods were added in ES8. These methods convert the object into an array and then use array looping methods to iterate over that array.

The simplest and most popular way to iterate over an object’s keys and values is using the for. in loop:

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > for (const key in birds)  console.log(`$key> -> $birds[key]>`) > // owl -> 🦉 // eagle -> 🦅 // duck -> 🦆 // chicken -> 🐔 

The for. in loop works in all modern and old browsers, including Internet Explorer 6+. The only issue with the for. in loop is it iterates through the properties in the prototype chain. Since the JavaScript object inherits properties from its prototype, the for. in loop will iterate over those properties as well. However, you can use the hasOwnProperty() method to exclude inherited properties:

for (const key in birds)  if (birds.hasOwnProperty(key))  console.log(`$key> -> $birds[key]>`) > > 

The Object.keys() method takes an object as input and returns an array of the object’s own enumerable properties names:

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > const keys = Object.keys(birds) console.log(keys) // [ 'owl', 'eagle', 'duck', 'chicken' ] 
keys.forEach(key =>  console.log(`$key> -> $birds[key]>`) >) // owl -> 🦉 // eagle -> 🦅 // duck -> 🦆 // chicken -> 🐔 

The Object.values() method, unlike Object.keys() , returns an array of the given object’s own enumerable properties values:

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > Object.values(birds).forEach(item => console.log(item)) // 🦉 // 🦅 // 🦆 // 🐔 

The Object.entries() method returns an array of arrays, whereby each nested array has two elements. The first element is the property and the second element is the value.

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > const entries = Object.entries(birds) console.log(entries) // [ // [ 'owl', '🦉' ], // [ 'eagle', '🦅' ], // [ 'duck', '🦆' ], // [ 'chicken', '🐔' ] // ] 

To iterate over the nested array returned by Object.entries() , use the for. of loop or the forEach() method as shown below:

// => `for. of` Loop for (const [key, value] of Object.entries(birds))  console.log(`$key> -> $value>`) > // => `forEach()` Loop Object.entries(birds).forEach(([key, value]) =>  console.log(`$key> -> $value>`) >) 

You might also like.

Источник

How to List the Properties of a JavaScript Object

In this tutorial, two mostly used methods are presented, which will list the properties of a JavaScript object.

You can use the built-in Object.keys method which is supported in the modern browsers:

let keys = Object.keys(myObj);

Example:

w3docs logo

Javascript Object.keys method

To retrieve the list of the property names, you can do the following:

let getKeys = function (obj) < let keysArr = []; for (var key in obj) < keysArr.push(key); >return keysArr; >

Example:

w3docs logo

Javascript object list of the property names

Alternatively, you can replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. However, extending the prototype has some side effects and is not recommended.

You can also use the for. in construct to iterate over an object for its attribute names. However, doing it, you will iterate over all attribute names in the object’s prototype chain. To iterate only over the attributes of the object, you can use the hasOwnProperty() method like this:

for (var key in obj) < if (obj.hasOwnProperty(key)) < /* code here */ > >

Example:

w3docs logo

Javascript object hasOwnProperty() method

The Object.keys() method

The Object.keys() method returns the array of a specified object’s own enumerable property names. The property order is the same as in the case of looping over the properties of the object manually.

The hasOwnProperty() Method

The hasOwnProperty() method returns a boolean value that indicates if the object has the specified property as its own property or not. If the object contains the «key» property, a function is created. This would return true if it could find no keys in the loop, meaning the object is empty. If any key is found, the loop breaks returning false.

Источник

How to Get an Object’s Keys and Values in JavaScript

In JavaScript, getting the keys and values that comprise an object is very easy. You can retrieve each object’s keys, values, or both combined into an array.

The examples below use the following object:

Getting an object’s keys

The Object.keys() method returns an array of strings containing all of the object’s keys, sorted by order of appearance:

console.log(Object.keys(obj)); // Expected output: ["name", "age", "occupation", "level"]

Here, as well as in the following examples, we pass in the object from which the data is needed as a parameter.

Getting an object’s values

The Object.values() method returns an array of strings containing all of the object’s field values, sorted by order of appearance:

console.log(Object.values(obj)); // Expected output: ["Daniel", 40, "Engineer", 4]

Getting an object’s entries

The Object.entries() method returns an array of arrays. Each array consists of a pair of values. The first string is the name of a key in the object, the second is its corresponding value. In the example below, the first element in the array is [“name”, “Daniel”]. In this sub-array, “name” is the first key of the object obj, and “Daniel” is the first value of the object.

console.log(Object.entries(obj)); // Expected output: [["name", "Daniel"], ["age", 40], ["occupation", "Engineer"], ["level", 4]]

Tip: It is possible to recreate the original object using the return value of the Object.entries() method.

Reform an object

Given an array of key-value pairs as returned by Object.entries() , we can use the same output to recreate the original object. This is achieved with Object.fromEntries() :

const objEntries = Object.entries(obj); console.log(Object.fromEntries(objEntries)); // Expected output:

The Object.fromEntries() method forms an object out of an iterable argument. You cannot simply pass an array with two elements, as this is not the format returned by Object.entries() . The input to Object.fromEntries() needs to be an array of arrays, as provided in the example above. It is important to note, though, that, arrays that do not obey the “two items rule” will still be processed. You can see this in the following example:

const arr = [[4, 28, 167, «JavaScript»], [«One», «Two», «Three»], [«hello»]]; console.log(Object.fromEntries(arr)); // Expected output:

In the example above, the first array element has four items, the second array element has three items and the third array element has only one item. In each of these cases, only the first two items are used when forming an object. If there is only a single element present, the corresponding value of that element is undefined.

Related Articles:

Источник

How to Get All Property Values of a JavaScript Object

To detect all the property values of object without knowing the key can be done in a number of ways depending on browsers. The majority of browsers support ECMAScript 5 (ES5). Let’s see what methods can be used for getting the property value based on different specifications.

ECMAScript 5+

You can use the methods below in the browsers supporting ECMAScript 5+. These methods detect values from an object and avoid enumerating over the prototype chain:

w3docs logo

Javascript detect values from an object

To make the code more compact, use the forEach:

w3docs logo

Javascript detect values from an object use forEach

The following method builds an array which contains object values:

w3docs logo

Javascript detect values from an object builds an array

To make those using Object.keys safe against null, then you can run:

w3docs logo

Javascript detect values from an object builds an array

Object.keys returns enumerable properties. Using Object.keys is usually effective for iterating over simple objects. If you have something with non-enumerable properties to work with, you can use:

Object.getOwnPropertyNames instead of Object.keys.

ECMAScript 2015+ ( ES6)

It is easier to iterate Arrays with ECMAScript 2015. You can use the following script when working with values one-by-one in a loop:

w3docs logo

Javascript detect values one-by-one from an object

To use ECMAScript 2015 fat-arrow functions and to map the object to an Array of values can become a one-liner code:

w3docs logo

Javascript detect values from an object

The ECMAScript 2015 specification introduces Symbol, instances of which can be used as property names. You can use the Object.getOwnPropertySymbols to get the symbols of an object to enumerate over. The new Reflect API from ECMAScript 2015 provides Reflect.ownKeys returning a list of property names and symbols.

Object.values

This just adds a method to object. Using fat-arrow functions can be a one-liner:

w3docs logo

Javascript detect values from an object using Object.values

Object.values = obj => Object.keys(obj).map(key => objJavascript list object values); //which you can now use like // [‘one’, ‘two’, ‘three’] let values = Object.values(< a: 'one', b: 'two', c: 'three' >); console.log(values);

If you do not want to use shimming when a native Object.values exists, then you can run:

w3docs logo

Javascript detect values from an object using Object.values

Object.values = Object.values || (obj => Object.keys(obj).map(key => objJavascript list object values)); let values = Object.values(< a: 'one', b: 'two', c: 'three' >); console.log(values);

ECMAScript 2017+

This specification adds Object.values and Object.entries where both return arrays. Object.values can be used with a for-of loop:

w3docs logo

Javascript detect values from an object used Object.values

If you want to use both the key and the value, then you can use the Object.entries:

w3docs logo

Javascript detect values from an object used Object.entries

Object.keys/values/entries methods have similarity with for..in loop. They all ignore properties that apply Symbol(. ) as a key. When you need symbols, you can use a separate method Object.getOwnPropertySymbols which returns an array consisting of only symbolic keys.

BookDuck

  • How to Count the Number if Keys/Properties of a JavaScript object
  • How to Check for the Existence of Nested JavaScript Object Key
  • How to Check if an Object has a Specific Property in JavaScript
  • How to Loop Through or Enumerate a JavaScript Object
  • How to Get the First Key Name of a JavaScript Object
  • How to Check if a Value is an Object in JavaScript
  • How to Check if a Key Exists in JavaScript Object
  • How to List the Properties of a JavaScript Object
  • How to Convert Arguments Object to an Array
  • How to Check if JavaScript Object is Empty
  • How to Sort JavaScript Object by Key
  • JavaScript Object.keys, Values, Entries
  • JavaScript Proxy and Reflect
  • JavaScript Loops: while and for
  • Javascript Objects
  • JavaScript Array methods
  • JavaScript Symbol Types
  • JavaScript Arrays

Источник

Читайте также:  Css animation position absolute
Оцените статью