The Wayback Machine - https://web.archive.org/web/20241126195634/https://www.geeksforgeeks.org/how-to-convert-string-of-objects-to-array-in-javascript/
Open In App

How to Convert String of Objects to Array in JavaScript ?

Last Updated : 30 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored in a file.

Using JSON.parse() Method

The most common and straightforward way to convert a string of objects to an array of objects is by using JSON.parse() method. This method parses a JSON string into a JavaScript object or array.

Example: This example shows the use of the above-mentioned approach.

JavaScript
let str = '[{"company":"Geeks", "contact":"+91-9876543210"}, 
  {"address":"sector 136", "mail":"xys@geeksforgeeks.org"}]';
let arr = JSON.parse(str);

console.log(arr);

Output
[
  { company: 'Geeks', contact: '+91-9876543210' },
  { address: 'sector 136', mail: 'xys@geeksforgeeks.org' }
]

Using eval() Method

Another approach to convert a string of objects to an array is by using the eval() function. However, this method is generally not recommended due to security risks associated with executing arbitrary code.

Example: This example shows the use of the above-explained approach.

JavaScript
let str = '[{"company":"Geeks", "contact":"+91-9876543210"}, 
  {"address":"sector 136", "mail":"xys@geeksforgeeks.org"}]';

let arr = eval(str);

console.log(arr);

Output
[
  { company: 'Geeks', contact: '+91-9876543210' },
  { address: 'sector 136', mail: 'xys@geeksforgeeks.org' }
]

Using the Function Constructor

Another method to convert a string of objects to an array of objects is by using the Function constructor. This method is safer than eval() as it creates a new function and doesn't have access to the local scope.

Example: This example shows the use of the Function constructor to convert a string of objects to an array of objects.

JavaScript
let str = '[{"company":"Geeks", "contact":"+91-9876543210"}, {"address":"sector 136", "mail":"xys@geeksforgeeks.org"}]';
let arr = (new Function('return ' + str))();

console.log(arr);

Output
[
  { company: 'Geeks', contact: '+91-9876543210' },
  { address: 'sector 136', mail: 'xys@geeksforgeeks.org' }
]

By Spliting JSON into Components

This method splits the JSON string into components and reconstructs the objects. It is a more manual approach and assumes that the JSON string is well-formed and simple.

Example:

JavaScript
function parseStringToArrayOfObjects(str) {
    // Remove surrounding brackets and extra spaces
    str = str.trim().slice(1, -1).trim();
    const objectStrings = str.split(/(?<=\}),\s*(?=\{)/);
    let result = [];
    function parseObjectString(objectStr) {
        // Remove leading and trailing spaces and curly braces
        objectStr = objectStr.trim().slice(1, -1).trim();

        // Initialize the object
        let obj = {};
        let key = '';
        let value = '';
        let inKey = true;
        let inString = false;
        let isEscaped = false;

        for (let i = 0; i < objectStr.length; i++) {
            let char = objectStr[i];

            if (char === '\\') {
                // Handle escaped characters
                isEscaped = !isEscaped;
                value += char;
                continue;
            }

            if (char === '"' && !isEscaped) {
                inString = !inString;
                if (!inString) {
                    if (inKey) {
                        key = value;
                    } else {
                        obj[key] = value;
                    }
                    value = '';
                    inKey = !inKey;
                }
                continue;
            }

            if (inString) {
                value += char;
            } else if (char === ':') {
                inKey = false;
            } else if (char === ',') {
                if (!inKey) {
                    obj[key] = value;
                    value = '';
                    inKey = true;
                }
            } else if (char === ' ' || char === '\n' || char === '\t') {
                // Ignore whitespace
                continue;
            } else {
                value += char;
            }

            isEscaped = false;
        }

        if (key && !inKey) {
            obj[key] = value;
        }

        return obj;
    }

    // Parse each object string and add it to the result array
    for (let objectStr of objectStrings) {
        result.push(parseObjectString(objectStr));
    }

    return result;
}

const str = '[{"company":"Geeks", "contact":"+91-9876543210"}, {"address":"sector 136", "mail":"xys@geeksforgeeks.org"}]';

const arr = parseStringToArrayOfObjects(str);

console.log(arr);

Output
[
  { company: 'Geeks', contact: '+91-9876543210' },
  { address: 'sector 136', mail: 'xys@geeksforgeeks.org' }
]



Previous Article
Next Article

Similar Reads

How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
8 min read
How to Convert Object Containing Objects into Array of Objects using Lodash?
Lodash is a JavaScript utility library that provides predefined functions to make code more readable and cleaner. These functions are optimized for performance, often being faster than native JavaScript methods for complex operations.We will learn how to convert an object containing objects into an array of objects using Lodash. There are two appro
4 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing Set for Efficient FilteringUsi
3 min read
How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
7 min read
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
5 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
7 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to updating an array of objects with another array of objects in the Lodash library: Table of Content Using lodash _.merge() function Using lodash _.mergeWith()
4 min read
How to convert CSV string file to a 2D array of objects using JavaScript ?
A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format. In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript. Given a comma-separated values (CSV) string to a 2D array, using Javascript
4 min read
Write a program to convert an array of objects to a CSV string that contains only the columns specified using JavaScript
When we want to store multiple values in one variable then instead of a variable, we use an array. which allows you to store multiple types of data for example you could have a string, an integer, etc. In this article, we will learn to convert the array objects to CSV string data. Given array objects ( key: value ) to CSV string comma-separated val
3 min read
How to Convert String to Array of Objects JavaScript ?
Given a string, the task is to convert the given string to an array of objects using JavaScript. It is a common task, especially when working with JSON data received from a server or API. Below are the methods that allow us to convert string to an array of objects: Table of Content Using JSON.parse() MethodUsing String Splitting and Object Construc
5 min read
Convert JSON String to Array of JSON Objects in JavaScript
Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information. There are two approaches to solving this problem, which are discussed belo
2 min read
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to convert an array of objects to a map in JavaScript:
2 min read
Extract unique objects by attribute from array of objects
Given an array of objects and the task is to return the unique object by the attribute. Examples: Input: [ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 } ]Output:[ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 } ]Approach: Let's assume that name is an attribute that di
4 min read
Get list of Duplicate Objects in an Array of Objects
Finding duplicates in an array of objects is a common task in JavaScript, especially when dealing with data manipulation and validation. This will guide you through the process of identifying duplicate objects in an array using various techniques. Understanding the ProblemLet's assume we have an array of objects where each object has a set of key-v
4 min read
How to convert a map to array of objects in JavaScript?
A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods for converting a map into an array of objects in J
7 min read
How to Convert an Object into Array of Objects in JavaScript?
Converting an object into an array of objects can be done by converting the properties and values of the object into individual objects within an array. Below are the approaches to converting an object into an Array of objects using JavaScript: Table of Content Using Object.values() methodUsing Object.keys() methodUsing Object.entries() methodUsing
4 min read
How to Convert an Array of Objects to a Map in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Example:Input Array: [ { type: 'Company', name: 'GeeksforGeeks' }, { type: 'Cri
7 min read
Convert Dictionary into an Array of objects in JavaScript
In JavaScript, dictionaries also known as objects are used to store key-value pairs. But sometimes you might need to convert this data into an array of objects so that you can handle or utilize particular parts more easily. Below are the multiple ways of converting a Dictionary into an Array of objects in JavaScript: Table of Content Using Object.k
4 min read
What is the difference between Host objects and Native objects ?
In this article, we will learn about what are Host objects and Native objects, and their differences. JavaScript objects are broadly classified into 2 categories - native javascript objects and host javascript objects. Native objects: Native javascript objects are standard javascript objects which are provided by javascript itself. They are also kn
2 min read
How to Convert an Array of Objects into an Array of Arrays ?
An Array of objects is an array that contains multiple objects as its elements which can be converted into an array of arrays i.e. an array that contains multiple arrays as its elements. There are several methods listed below to achieve this task. Table of Content Using Object.keys() and Object.values() methodsUsing Javascript map() methodUsing Jav
3 min read
Sort Array of Objects By String Property Value in JavaScript
Sorting arrays of objects based on a string property can be helpful for handling user data or dynamic lists. Here are different ways to sort an array of Objects By String Property Value. 1. Using localeCompare() Method – Most UsedThe JavaScript localeCompare() method returns a number indicating whether this string comes before, or after, or is the
3 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How to Convert an Array of Keys into a Union Type of Objects ?
We can convert an array of keys into a union type of objects in typescript using mapped types or object types. The process involves dynamically creating types based on the provided array of keys, resulting in a union type that represents all possible combinations of objects with those keys. Table of Content Using Mapped TypesUsing Objects TypesUsin
4 min read
How to Convert an Array of Objects into Object in TypeScript ?
Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript. We are given an array of objects and we have to convert this array into a single ob
3 min read
Difference between Array and Array of Objects in JavaScript
ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored in an array. Example: In thi
3 min read
How to group objects in an array based on a common property into an array of arrays in JavaScript ?
In this article, we will try to understand how we may easily group objects in an array based on a common property into an array of arrays in JavaScript with the help of an example itself. Grouping objects in an array based on a common property into an array of arrays in JavaScript. Organize data by shared property for efficient data manipulation. S
6 min read
How to create an array of partial objects from another array in JavaScript ?
Creating an array of partial objects from another array is a useful technique in JavaScript, especially for data transformation and manipulation. This guide covers various methods to efficiently create these arrays, enhancing your ability to work with complex data structures. Importance of Creating Partial Objects:Creating partial objects is crucia
6 min read
Are String Objects in JavaScript?
Strings in JavaScript are one of the primitive data types, alongside numbers, booleans, null, undefined, bigint, and symbols. Unlike objects, primitives do not have methods or properties of their own. However, when you attempt to call a method or access a property on a string, JavaScript automatically wraps the string in a String object to provide
2 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
How to convert Integer array to String array using JavaScript ?
The task is to convert an integer array to a string array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. Approaches to convert Integer array to String array:Table of Content Approach 1: using JavaScript array.map() and toString() methodsApproach 2: Using JavaScript Array.join() and split() methodsAp
2 min read
three90RightbarBannerImg