Open In App

How to Convert String to Array of Objects JavaScript ?

Last Updated : 15 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using JSON.parse() Method

If the string is in JSON format, you can use the JSON.parse() method to convert it into an array of objects. JSON.parse() method converts the JSON string into an array of objects. The string must be in valid JSON format for JSON.parse() to work correctly.

Example: Parsing JSON String to Array of Objects which involves parsing a JSON string into an array of objects and then logging the resulting array.

JavaScript
const str = 
    '[{"name":"xyz", "age":30}, {"name":"abc", "age":25}]';

const arrayOfObjects = JSON
    .parse(str);

console.log(arrayOfObjects);

Output
[ { name: 'xyz', age: 30 }, { name: 'abc', age: 25 } ]

Using String Splitting and Object Construction

If the string is not in JSON format, you can manually split the string and construct objects to create the array, split() method splits the string into an array of individual records based on the semicolon delimiter. The map() is used to iterates over each record and splits it into name and age using the comma delimiter. An object is constructed for each record with name and age properties, and age is converted to an integer using parseInt(age).

Example: Converting String Records to Array of Objects it involves splitting a string of records, mapping each record to an object with name and age properties, and then logging the resulting array of objects.

JavaScript
const dataString = 'xyz, 30; abc, 25';
const records = dataString
    .split(';');

const arrayOfObjects = records
    .map(record => {
        const [name, age] = record
            .split(',');
        return { name, age: parseInt(age) };
    });

console.log(arrayOfObjects);

Output
[ { name: 'xyz', age: 30 }, { name: ' abc', age: 25 } ]

Using Regular Expressions

For more complex string formats, you can use regular expressions to extract data and convert it into an array of objects. The regular expression /Name: ([^,]+), Age: (\d+)/g is used to match the pattern in the string. The while loop iterates over each match found by the regular expression. For each match, an object is constructed with name and age properties, and age is converted to an integer using parseInt(match[2]). The object is then added to the arrayOfObjects.

Example: Converting JSON String to Array of Objects it involves parsing a JSON string into an array of objects.

JavaScript
const str = 'Name: xyz, Age: 30; Name: abc, Age: 25';
const regex = /Name: ([^,]+), Age: (\d+)/g;
const arrayOfObjects = [];
let match;
while ((match = regex
    .exec(str)) !== null) {
    arrayOfObjects
        .push({
            name: match[1],
            age: parseInt(match[2])
        });
}

console.log(arrayOfObjects);

Output
[ { name: 'xyz', age: 30 }, { name: 'abc', age: 25 } ]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads