The task is to convert an Object {} to an Array [] of key-value pairs using JavaScript.
Introduction: Objects, in JavaScript, is it’s most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol). Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types, while the array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.
Introduction: Objects, in JavaScript, is it’s most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol). Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types, while the array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.
We can convert an Object {} to an Array [] of key-value pairs using methods discussed below:
Method 1: In this method, we will use Object.keys() and map() to achieve this.
Method 1: In this method, we will use Object.keys() and map() to achieve this.
Approach: By using Object.keys(), we are extracting keys from the Object then this key passed to map() function which maps the key and corresponding value as an array, as described in the below example.
Syntax:
Syntax:
Object.keys(obj)
Parameter:
obj: It is the object whose enumerable properties are to be returned.map(function callback(currentValue[, index[, array]]){ // Return element for new_array }
Parameter:
callback: Function that produces an element of the new Array
No comments:
Post a Comment