Get key value array object

The objects in Javascript are containers for named values called properties or methods. The object contains keys & values. To lớn access the object’s keys, use the keys() method. For example, the keys() method in JavaScript is used lớn return a simple array’s enumerable properties.

Object.keys in JavaScript

The Object.keys() is a built-in JavaScript function that returns an array of the given object’s property names in the same order as we get with a standard loop. The Object.keys() method takes an object as an argument and returns the array of strings representing all the enumerable properties of a given object.

Bạn đang xem: Get key value array object

The Object keys() function returns the array whose elements are strings corresponding lớn the enumerable properties found directly upon the object.


An ordering of the properties is the same as that given by an object manually in the loop is applied lớn the properties.

Syntax

Object.keys(obj)

Arguments

The obj parameter is required, & its properties are to be returned.


Return Value

The return value is an array of strings representing all the enumerable properties of a given object.


Example

To perform the Object.keys() example, you installed Node.js in your machine. If you have not installed then install Node.js and NPM. It is not compulsory since you can use the online editor or browser. But if you want to lớn run it locally, you should install it.

Let us take a simple example.

// app.jslet obj = name: 'Krunal', education: 'IT Engineer' ;console.log(Object.keys(obj));Save the file and run the file by typing the node app in the terminal.

*

So, in the above example, we get an array of object keys. We can bởi the same with an array. We can get the array keys as well.

// app.jslet objArr = < 'apple', 'microsoft', 'amazon', 'alphabet', 'tencent', 'alibaba'>;console.log(Object.keys(objArr));So, here we have defined an array. Next, we will get the keys khổng lồ each element in the returned array.

*

Non-enumerable properties

The Object.keys() will only return the keys of enumerable properties. An example of a function property of an object is the Non-enumerable property. Therefore, we will not get the keys to that property.

Let us take an example.

// app.jslet myObj = Object.create(, getName: value: function () return this.name; );myObj.name = 'krunal';console.log(Object.keys(myObj));

*

How to lớn get a length of Object

To get the length of an object in Javascript, use the length property. Everything in JavaScript is an Object.

You can define the string object, the array object, or an Object constructor in JavaScript lớn create the object and showroom properties & values. Sometimes, you would also require knowing the length of an Object. 

// app.jslet unorderedData = real_name: 'Millie Bobby Brown', character_name: 'Eleven', series: 'Stranger Things';console.log(Object.keys(unorderedData).length)See the following output.

➜ es git:(master) ✗ node app3➜ es git:(master) ✗So, this is how to calculate or count how many properties have a JavaScript object.

Object.keys() and Array.forEach()

JavaScript does not have Object.forEach() method. So, khổng lồ iterate through all the keys, use the Array.forEach() function.

See the following example.

// app.jslet data = real_name: 'Millie Bobby Brown', character_name: 'Eleven', series: 'Stranger Things';Object.keys(data).forEach(item => console.log(item););See the following output.

*

We can use the Object.values() function if we want the object’s values.

Sorting Object by keys

All methods that iterate over property keys vày so in the same order:

First of all, The array indices are sorted numerically.Then all string keys (that are not indices) are in the order they were created.Finally, all symbols are in the order in which they were created.

If we want lớn sort the Javascript Object Keys(), we need khổng lồ use the ES6 higher-order function.

See the following example.

// app.jslet unorderedData = real_name: 'Millie Bobby Brown', character_name: 'Eleven', series: 'Stranger Things';console.log(JSON.stringify(unorderedData));const orderedData = ;Object.keys(unorderedData).sort().forEach(function(key) orderedData = unorderedData;);console.log(JSON.stringify(orderedData));See the following output.

Xem thêm: Người Môi Mỏng - Đàn Ông Môi Mỏng Nói Lên Điều Gì

➜ es git:(master) ✗ node app"real_name":"Millie Bobby Brown","character_name":"Eleven","series":"Stranger Things""character_name":"Eleven","real_name":"Millie Bobby Brown","series":"Stranger Things"➜ es git:(master) ✗You can see that our Object keys() are now sorted according lớn the alphabet.

Object keys map in JavaScript

This is how you can rename your object keys using the Array.map() method.

// app.jslet obj = 11: 'eleven', 21: 'mike', 10: 'will' ;Object.keys(obj).map(function (old_key, index) let new_key = old_key * 11; if (old_key !== new_key) Object.defineProperty(obj, new_key, Object.getOwnPropertyDescriptor(obj, old_key)); delete obj; );console.log(obj);See the output.

➜ es git:(master) ✗ node app '110': 'will', '121': 'eleven', '231': 'mike' ➜ es git:(master) ✗The above code will modify the object.

If you want lớn create a new object & do not modify the old object, write the following code.

// app.jslet obj = 11: 'eleven', 21: 'mike', 10: 'will' ;const newObject = ;Object.keys(obj).map(function (old_key, index) let new_key = old_key * 11; delete Object.assign(newObject, : obj ););console.log(newObject);See the output.

➜ es git:(master) ✗ node app '110': 'will', '121': 'eleven', '231': 'mike' ➜ es git:(master) ✗So, we have changed the keys of the object. We have also used the delete operator and Object.assign() method.

So, this is how you can change javascript object keys.

A non-optimized way would be,

// app.jso< new_key > = o< old_key >;delete o< old_key >;You could wrap the work in a function and assign it khổng lồ the Object prototype. Maybe use the fluent interface style khổng lồ make multiple renames flow.

Object.prototype.renameProperty = function (oldName, newName) // vì chưng nothing if the names are the same if (oldName === newName) return this; // check for the old property name khổng lồ avoid a ReferenceError in strict mode. If (this.hasOwnProperty(oldName)) this = this; delete this; return this;;

Javascript Object keys to lớn array

We can get the array of keys using the Object.keys() method.

// app.jslet obj = 'alpha': 'Google', 'instagram': 'Facebook';let keys = Object.keys(obj);console.log(keys);See the output.

➜ es git:(master) ✗ node app< 'alpha', 'instagram' >➜ es git:(master) ✗You can use the $.map for the jquery library.

Accessing nested data structures in Javascript

The nested data structure is the array or an object which refers to lớn other arrays or objects; for example, its values are arrays or objects.

Such data structures can be accessed by applying dot notation or bracket notation consecutively.

Here is an example:

// app.jsconst info = code: 11, items: < id: 1, name: 'Eleven' , id: 2, name: 'Krunal' >;Let’s assume that we want khổng lồ access the name of the second item.

Here is how we can vị it.

As we can see, the info is an object; hence we can access its properties using dot notation. The items’ property is accessed as follows.

info.itemsThe value is an array. Lớn access the second element of an array, we have khổng lồ use bracket notation:

info.items<1>This value is the object, and we use the dot notation again khổng lồ access the name property.

const info_name = info.items<1>.name;Alternatively, we could have used the bracket notation for any properties, mainly if the name contained characters that would have made it invalid for dot notation usage.

const item_name = info<'items'><1><'name'>;

Polyfill

If we want to địa chỉ cửa hàng compatible Object.keys() support in older environments that bởi vì not support it, copy the following snippet.

if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !( toString: null ).propertyIsEnumerable('toString'), dontEnums = < 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' >, dontEnumsLength = dontEnums.length; return function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) throw new TypeError('Object.keys called on non-object'); var result = <>, prop, i; for (prop in obj) if (hasOwnProperty.call(obj, prop)) result.push(prop); if (hasDontEnumBug) { for (i = 0; i

Browser Support

FEATUREBASIC SUPPORT
Chrome45
EdgeYes
Firefox25
Internet ExplorerNo
Opera32
Safari8
Android WebViewYes
Chrome for AndroidYes
Edge mobileYes
Firefox for Android4
Opera AndroidYes
iOS Safari8
That is it for this tutorial.