Divide the string into a collection of individual elements

Recently, I received a string from the backend that looks like this:

var string = "{name: Hello, age: 20}, {name: Nadia, age: 30}"
. To transform it into an object, I attempted to push it into an empty array using the following code:

var array = [];
var array1 = array.push(string);

However, the result after appending to the array was not what I expected:

Array [
      "{name: Hello, age: 20}, 
       {name: Nadia, age: 30}
       {name: Nadia, age: 30}
       {name: Nadia, age: 30}
       {name: Nadia, age: 30}"
]

What I really wanted was this:

Array [
          "{name: Hello, age: 20}", 
          "{name: Nadia, age: 30}",
          "{name: Nadia, age: 30}",
          "{name: Nadia, age: 30}",
          "{name: Nadia, age: 30}"
    ]

I tried using split(","), but each object got separated individually. Can anyone help me achieve the desired outcome? I'm still learning and would appreciate any guidance.

UPDATE: I followed the solution provided, but it didn't quite give me the result I was aiming for. The method returned two objects, with the second one being a combination of objects. Here's how the output looked using the suggested approach:

Array [
          "{name: Hello, age: 20}", 
          "{name: Nadia, age: 30}
           {name: Nadia, age: 30}
           {name: Nadia, age: 30}
           {name: Nadia, age: 30}"
    ]

Unfortunately, I have requested my backend colleague to adjust the JSON return, but they are unable to make changes. For now, I must find a solution on the frontend side to handle this issue.

Answer №1

Although this solution may seem a bit unrefined, it still gets the job done. Feel free to test it out:

let str = "{name: Hello, age: 20}, {name: Nadia, age: 30}, {name: Nadia, age: 30}, {name: Nadia, age: 30}";
let x = str.replace('}, ', '}/').split('/');
console.log(x);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Searching Json by keyword in PHP: A step-by-step guide

I am encountering an issue with searching through a JSON file. Currently, I am trying to search and display faculties based on the entered word, but the search only works when I type in the full name. How can I make the search function work if I only enter ...

MongoDB does not return any results for the query and returns

I am facing an issue while trying to retrieve information from my mongodb database. Despite successfully fetching data from the "users" collection, I keep getting an empty object for other collections. var mongoose = require('mongoose'); var Sch ...

Display Vue component depending on specified attribute

I have a block of code that I am working with: <div> <b-card no-body> <b-tabs pills card vertical no-key-nav v-model="step"> <b-tab title="Subject" v-for="animal in animals" :key="animal&q ...

How can I use a string argument in JavaScript to sort an array of objects by that specific value?

Currently, I am implementing React and facing a challenge with creating a reusable sorting component. This component is meant to sort an array of objects based on a specific property field. For instance, imagine having an array of objects with properties a ...

Creating an object and setting its prototype afterwards

While exploring examples and questions online about prototypal inheritance, I noticed that most of them involve assigning prototypes to constructor functions. One common pattern is shown in the code snippet below: Object.beget = function (o) { var F = ...

Require assistance in generating three replicas of an object rather than references as it currently operates

I am encountering an issue with my code where I seem to be creating 4 references to the same object instead of 4 unique objects. When I modify a value in groupDataArrays, the same value gets updated in groupDataArraysOfficial, groupDataArraysValid, and gro ...

Newbie in Distress: Help Required Due to Server Error

Currently working on the contacts page for a website and I need the div element to disappear once an email is successfully sent. In order to hide a Div element using Javascript, I created the following function: function hideDiv(){ document.getElement ...

Getting a page element by its id with QWebEngineView is a simple task that can be

Is there a way to access the page ElementById in order to input a value? import sys from PyQt5 import QtWebEngineWidgets from PyQt5.QtCore import * from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import * from PyQt5.QtWidgets import QAction from PyQt ...

Is it possible to validate link clicks and integrate PHP within JavaScript functions?

Before anyone mentions security concerns, please refrain. Imagine I have an index.php. This page contains several links to 'home.php', each with different data stored in the href attributes. For example: Link 1: 'home.php?data=1&count ...

Determining the minimum and maximum values of a grid using props in a React component

I have created a code for a customizable grid screen that is functioning perfectly. However, I am facing an issue where I want the minimum and maximum size of the grid to be 16 x 100. Currently, when a button is clicked, a prompt window appears asking for ...

The attempted decoding of a JSON object was unsuccessful. The provided JSON is not valid

I've encountered an unusual issue In my program, I am sending a JSON string through a socket: json_string = JSONEncoder().encode({ "id_movil": str(id_movil), "correo": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

Error: Unable to access attributes of an undefined object (specifically 'headers') in the Next.js evaluation

I encountered an issue with next js TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:61) Snippet of the pro ...

Converting Java collections into JSON format

My task requires my program to generate JSON data in the following format: { "success": { "code": 1, "desc": "success" }, "response": { "res1": [ { "Item": "item1", "Description": [ ...

Struggling to generate distinct charts with chart.js

I need assistance in displaying individual charts for different sensors on a web page. Currently, when multiple SensorData is selected by the user, it generates a single "multi chart" which is not the desired outcome. Below is the code snippet responsible ...

Problems arise when JQuery fails to function properly alongside ajax page loading

While utilizing ajax to load the page, I encountered an issue where the jQuery on the loaded page template was not functioning until the page was manually refreshed. The ready function being used is: jQuery(document).ready(function() { jQuery(' ...

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

Setting up a variable that has been previously declared outside of the jQuery $.getJSON callback function

When my script executes an Ajax request using jQuery, the data it receives is json_encoded by a server-side script written in PHP. This JSON data is then stringified and parsed with jQuery to create a recordCollection. Each item in the recordCollection is ...

Extract token from the URL and then use Axios in Vue.js to send it to the POST API

Hey there, I'm in need of extracting a token from the URL http://192.168.178.25:8080/register?token=eyJhbGciOiJIUzI... and then making a POST request to the API to confirm the account. I've attempted this but encountered a SyntaxError on the ...

What are the steps to implementing AOP in node.js?

I am facing a challenge with implementing AOP in node.js: Imagine I have an application in a script named server.js, and I need to track its functions. Here is the code snippet: var express = require('express'); var app = express(); app.get(& ...

Exploring the world of React and Material Ui

As I delve into working with Material Ui in React, I am encountering difficulties when trying to customize the components. For instance, let's take a look at an example of the AppBar: import React from 'react'; import AppBar from 'mat ...