Converting an array of strings into a JSON object using JavaScript

Below is an array that needs to be transformed into a JSON object:

data = [
    "Id = 2",
    "time = 10:59",
    "Topic = xxxxxxxxxxxxxxxx",
    "GUEST3",
    "Role = GS",
    "Infos = Connecticut",
    "GUEST4",
    "Role = HS",
    "Infos = Delaware",
    "GUEST5",
    "Role = CS",
    "Infos = Hawaii"
]   

I am looking to convert it into the following JSON object structure:

data = [   
 {    
    Id : 2,  
    time : '10:59',
    Topic : 'xxxxxxxxxxxxxxxx', 
    GUEST3:
           {
             Role : 'GS',
             Infos : 'Connecticut',
           }
   GUEST4:
           {
            Role : 'HS',
            Infos : 'Delaware',  
   GUEST5:
           {
            Role : 'CS',
            Infos : 'Hawaii'
           }
 }

Answer №1

Find below a code snippet to achieve the desired outcome.

The explanation is provided within the code comments, but essentially it iterates through each string in the array and determines whether it's a key-value pair or another layer of the object.

const data = ["Id = 2", "time = 10:59", "Topic = xxxxxxxxxxxxxxxx", "GUEST3", "Role = GS", "Infos = Connecticut", "GUEST4", "Role = HS", "Infos = Delaware", "GUEST5", "Role = CS", "Infos = Hawaii"];

// Initializing new object
let obj = {};
// Keeping track of current object level
let level;

// Iterating through the array
for (let item of data) {
    if (item.includes('=')) {
        let split = item.split('=');
        let key = split[0].trim();
        let cont = split[1].trim();
        
        if (level) {
            obj[level][key] = cont
        } else {
            obj[key] = cont
        }
    } else {
        level = item;
        obj[item] = {};
    }
}

console.log(obj)

If you have any trouble understanding the code, feel free to ask for clarification.

EDIT:

An updated solution combining elements from previous answers.

const data = ["Id = 2", "time = 10:59", "Topic = xxxxxxxxxxxxxxxx", "GUEST3", "Role = GS", "Infos = Connecticut", "GUEST4", "Role = HS", "Infos = Delaware", "GUEST5", "Role = CS", "Infos = Hawaii"]

let topLevelObj = currentObj = {};
data.map(a => a.split(' = ')).forEach(e => {e.length > 1 ? currentObj[e[0]] = e[1] : currentObj = topLevelObj[e] = {}});
console.log(topLevelObj);

Answer №2

It appears that your input array is structured in a non-standard way. If this is indeed the format you receive your data in, you can utilize the provided code snippet to process it accordingly. However, I would strongly advise double-checking and exploring options to modify the backend system (or the source of this data) to provide a standard JSON string or JavaScript object for better compatibility.

var data = [
  "Id = 2",
  "time = 10:59",
  "Topic = xxxxxxxxxxxxxxxx",
  "GUEST3",
  "Role = GS",
  "Infos = Connecticut",
  "GUEST4",
  "Role = HS",
  "Infos = Delaware",
  "GUEST5",
  "Role = CS",
  "Infos = Hawaii"
];

var result = {};
var putInto = result;
for (let token of data) {
  if (token.indexOf('=') != -1) {
    let nameValue = token.split('=');
    let name = nameValue[0].trim();
    let value = nameValue[1].trim();
    putInto[name] = value;
  } else {
    let child = {};
    result[token] = child;
    putInto = child;
  }
}

console.log(result)

Answer №3

To start off, ensure that the data is correctly formatted. One method is to structure it as an array of arrays.

const stringData = ["Id = 2","time = 10:59","Topic = xxxxxxxxxxxxxxxx","GUEST3","Role = GS" ,"Infos = Connecticut","GUEST4","Role = HS","Infos = Delaware","GUEST5","Role = CS","Infos = Hawaii"]

const formattedData = stringData.map(entry => entry.split('='))

Next, you can utilize something similar to _.fromPairs from lodash

const json = _.fromPairs(formattedData);

This will give you a plain JSON output. While it may not be exactly what you require, it's a good starting point.

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

Retrieving information from CRM online utilizing the Web API

Recently, I developed a webpage to serve as a survey for end users to provide feedback on the helpdesk technician's performance in resolving tickets. The webpage was constructed using HTML, CSS, JS, and PHP. Currently, the page requires access to two ...

"The Django querydict receives extra empty brackets '[]' when using jQuery ajax post to append items to a list in the app

Currently, I am tackling a project in Django where I am utilizing Jquery's ajax method to send a post request. The csrftoken is obtained from the browser's cookie using JavaScript. $.ajax({ type : 'POST', beforeSend: funct ...

Utilizing Vue3's draggable component to seamlessly incorporate items

My current project involves the use of the vue draggable package, and below you will find the complete component: <template> <div> <button class="btn btn-secondary button" @click="add">Add</button> ...

Looking for assistance with reviewing and optimizing Angular UI-Router implementation

I'm currently facing an issue with setting up routing for my angular portfolio. Despite checking my code against a previous app, I am unable to identify the error as there are no console logs when I compile. Can someone please review my code layout an ...

How can I prevent opening duplicate tabs of the same website simultaneously?

Is there a way to prevent users from accessing the same website page from multiple tabs? Could this be accomplished using JavaScript? ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

Is there a way to incorporate bubbles onto all of my y-axis values, as well as implement a mouseover feature for each one?

<!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none ; } .line { fill: none ...

Efficient way to handle nested variables in templates with Nunjucks or alternative approaches

Recently I've been exploring the world of gulp and nunjucks templating, specifically for creating emails. One challenge I'm facing is figuring out how to call a module/partial and assign different values to its attributes each time it's pro ...

JavaScript function to double the odd numbers

I'm attempting to extract the odd numbers from the given array and then double them using the reduce method, but I keep getting an undefined error. Can someone please offer some guidance? const multiplyOddByTwo = (arr) => { return arr.reduce(( ...

I would love to hear your suggestions for a custom select element plugin in jQuery

After browsing multiple options online, I decided to turn to the expertise of the Stack Overflow community to ask for recommendations based on personal experience. I am specifically in search of a plugin that can substitute a select element with a custo ...

Strategies for iterating through file inputs and organizing them into arrays

As a newcomer to C++, I am trying my best to learn, so please forgive any mistakes I may make. I have a file that contains data in the format of "String", "String", Character, and Number with 100 entries such as "Billy Joel A 96 Tim McCan B 70". I aim to ...

Showcasing two sets of data from an array using chart.js within a node.js environment

I am currently working on a project where I need to display two elements from an array - one as the label (e.g. "name of certain type of crop") and the other as the data itself (e.g. "quantity of the crop"). However, I am facing an issue where if the same ...

The issue of appending request URLs in the $.ajax function

Can anyone explain why jQuery.ajax() adds a parameter to the URL? I enabled cache, but it's still not working as expected. The console logs are not showing up and the request URL is being modified with &_=1396146406542. How can I remove this add- ...

Display only the selected index and conceal the rest

I am facing an issue where I have added a label and input in ng-repeat. The functionality works fine when the user clicks edit to show the input and hide the label. However, the problem arises when the user clicks on the new button as it displays the new i ...

Hide the button when you're not actively moving the mouse, and show it when you start moving it

How can I make my fixed positioned button only visible when the mouse is moved, and otherwise hidden? ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

Displaying threaded discussions in React

Below is an array that contains comments, and I am attempting to display them in a threaded manner by utilizing the parentId property. comments: [ { id: 1, parentId: null }, { id: 2, parentId: 1 }, { id: 3 ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...

obtain data from an array using Angular 5

i need assistance with retrieving values from an array. Below is my code snippet: this.RoleServiceService.getRoleById(this.id).subscribe(data => { this.roleData.push(data['data']); console.log(this.roleData); }) however, the resulting ar ...

What is the best way to merge multiple chunks of arrays into a single array

What I currently possess: let json = { key1: 'value1', key2: 'value2', key3: { title: 'yeah' } } let path = ['key3', 'title']; My goal is to concatenate segments of the 'path' array ...