Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert array of comma separated strings to array of objects?
Converting an array of comma-separated strings to an array of objects is a common task in JavaScript. This can be done using various methods depending on the structure of your data.
Understanding the Problem
When you have an array containing JSON strings, you need to parse each string into a JavaScript object. The most straightforward approach is using JSON.parse() combined with array methods.
Method 1: Using JSON.parse() with forEach
This method modifies the original array by parsing each JSON string:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array to Objects Conversion</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.sample, .result {
background: #f4f4f4;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
.result {
background: #e8f5e8;
}
button {
background: #007cba;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Convert Array of JSON Strings to Objects</h1>
<div class="sample">
<strong>Original Array:</strong>
<div id="original"></div>
</div>
<button onclick="convertArray()">Convert to Objects</button>
<div class="result">
<strong>Converted Objects:</strong>
<div id="result"></div>
</div>
<script>
let arr = [
'{"name":"Rohan", "age":12}',
'{"name":"Mohit", "age":22}',
'{"name":"Shawn", "age":18}',
'{"name":"Michael", "age":19}'
];
// Display original array
document.getElementById('original').innerHTML = arr.map(item =>
`<div>${item}</div>`
).join('');
function convertArray() {
// Convert each string to object
arr.forEach((item, index) => {
arr[index] = JSON.parse(item);
});
// Display converted objects
let resultHTML = arr.map(item =>
`<div>Name: ${item.name}, Age: ${item.age}</div>`
).join('');
document.getElementById('result').innerHTML = resultHTML;
}
</script>
</body>
</html>
Method 2: Using map() for Immutable Approach
This method creates a new array without modifying the original:
let jsonStrings = [
'{"name":"Alice", "city":"New York"}',
'{"name":"Bob", "city":"London"}',
'{"name":"Charlie", "city":"Tokyo"}'
];
// Convert to array of objects
let objectsArray = jsonStrings.map(jsonString => JSON.parse(jsonString));
console.log("Original strings:", jsonStrings);
console.log("Converted objects:", objectsArray);
// Access individual properties
objectsArray.forEach(person => {
console.log(`${person.name} lives in ${person.city}`);
});
Original strings: [
'{"name":"Alice", "city":"New York"}',
'{"name":"Bob", "city":"London"}',
'{"name":"Charlie", "city":"Tokyo"}'
]
Converted objects: [
{ name: 'Alice', city: 'New York' },
{ name: 'Bob', city: 'London' },
{ name: 'Charlie', city: 'Tokyo' }
]
Alice lives in New York
Bob lives in London
Charlie lives in Tokyo
Error Handling
When parsing JSON strings, it's important to handle potential errors:
let mixedArray = [
'{"name":"Valid", "age":25}',
'invalid json string',
'{"name":"Another Valid", "age":30}'
];
let convertedArray = mixedArray.map((item, index) => {
try {
return JSON.parse(item);
} catch (error) {
console.log(`Error parsing item ${index}: ${error.message}`);
return null; // or return a default object
}
}).filter(item => item !== null); // Remove failed conversions
console.log("Successfully converted:", convertedArray);
Error parsing item 1: Unexpected token 'i', "invalid json string" is not valid JSON
Successfully converted: [
{ name: 'Valid', age: 25 },
{ name: 'Another Valid', age: 30 }
]
Comparison of Methods
| Method | Modifies Original | Error Handling | Best For |
|---|---|---|---|
| forEach + JSON.parse | Yes | Manual | When you want to modify the original array |
| map + JSON.parse | No | Easy to add | Functional programming approach |
Conclusion
Converting JSON strings to objects is straightforward using JSON.parse(). Use map() for immutable transformations and always include error handling for robust applications.
