Combine two comma-separated strings in JavaScript to create an array of objects

I have two strings separated by commas that I want to transform into an array of objects.

{
 "id": "1,2,3",
 "name": "test 1, test 2, test 3"
}

Is there a way to convert this into the desired object format?

{
    "selectedDataConcepts": {
        "dataConcepts": [{
                "id": "1",
                "name": "test 1"
            },
            {
                "id": "2",
                "name": "test 2"
            },
            {
                "id": "3",
                "name": "test 3"
            }
        ]
    }
}

I've tried multiple approaches without success. Any help with finding a solution would be greatly appreciated.

Answer №1

If you visit this link, you could learn about using String.prototype.split to separate ids and names into arrays, which can then be utilized to achieve the desired outcome.

const data = { id: "1,2,3", name: "test1, test2, test3" };

const ids = data.id.split(',');
const names = data.name.replaceAll(' ', '').split(',')
const result = {
    selectedDataConcepts: {
        dataConcepts: ids.map((id, index) => ({id, name: names[index]}))
    }
}

console.log(result);

Answer №2

Here is an alternative method to accomplish this task...

const data = { id: "1,2,3", name: "test1, test2, test3" };

const { id, name } = data;
const ids = id.split(',');
const names = name.replaceAll(' ', '').split(',');

const selectedDataConcepts = {
  dataConcepts: ids.map((id, index) => ({id, name: names[index]}))
};

const result = { selectedDataConcepts };

console.log(result);

Answer №3

Experimenting with a more polished and easily readable method.

const data = { "id": "1,2,3", "name": "test 1, test 2, test 3"}

console.log({
    "selectedDataConcepts": {
        "dataConcepts": data.id.split(",").map((item, index) => {
            return {
                "id": data.id.split(",")[index],
                "name": data.name.split(",")[index].trim()
            }
        })
    }
})

Answer №4

One initial concept that can definitely use some enhancement:

function convertToDataConcepts(obj) {
  const idList = obj.id.split(',');
  const nameList = obj.name.replaceAll(' ','').split(',');
  const result = {selectedDataConcepts:[]};

  idList.forEach((id, index) => {
    result.selectedDataConcepts.push({id:idList[index], name: nameList[index]});
  });
  return result;
}

Answer №5

Here is a potential solution for you:

const data = { id: "x,y,z", name: "apple, orange, banana" };

const jsonData = {
    "selectedFruitData": {
        "fruits": data.name.split(',').map((fruit,i) => ({id:data.id.split(',')[i], name}))
    }
}
console.log(jsonData); 

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

Guide to displaying API data in HTML format

This university assignment involves working on a homework project where I need to utilize a public API in HTML. So far, I have successfully called the public API to display a list of radio channels in the left menu (without adding any click functionality). ...

Presentation of information with loading and error scenarios

How can we effectively display data in an Angular view, considering loading state and error handling? Imagine we are fetching a set of documents from our backend and need to present them in an Angular view. We want to address three possible scenarios by p ...

Validate if the user is actively scrolling; if not, automatically adjust the scroll position to the bottom

I am currently developing a chat site where the chat box updates every 200 milliseconds. I have managed to reposition the scrollbar to the bottom when a new message is loaded. However, I encountered a problem - whenever a user tries to scroll to the top, t ...

Tips on personalizing the formatting alert in Webclipse for Angular 2 using Typescript

Webclipse offers extensive formatting warnings for TypeScript code, such as detecting blank spaces and suggesting the use of single quotes over double quotes. However, some users find the recommendation to use single quotes annoying, as using double quotes ...

What prevents me from extending an Express Request Type?

My current code looks like this: import { Request, Response, NextFunction } from 'express'; interface IUserRequest extends Request { user: User; } async use(req: IUserRequest, res: Response, next: NextFunction) { const apiKey: string = ...

"Contrasting the Execution of a JavaScript Function in a .js File Versus an HTML

I'm struggling with calling a JavaScript function inside an HTML page. Interestingly, when I move the function into an external file and link it, everything works perfectly. Can someone provide assistance in resolving this issue? Below is the content ...

Setting up Jest

I'm currently attempting to integrate the Jest Testing framework into my React Native project. Unfortunately, I am encountering an error message: Failed to retrieve mock metadata: /Users/me/Documents/Development/project/node_modules/global/window.js ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

Is it possible for the HTML data attribute to store a direct link to a specific DOM element?

Can the HTML data- attributes be used to store a reference to another DOM element? As shown in this jQuery example: var domel1 = document.getElementById("#mydiv"); var domel2 = document.getElementById("#mydiv2"); $(domEl1).attr('data-domel', dom ...

Using jQuery and Ajax to fade in content after all images and other assets have finished loading

I've encountered an issue with loading pages via ajax for users with custom URLs. For example, a profile is usually found at http://example.com/users/Dan, but if a user has a custom URL like http://example.com/DansCustomURL, I need to fetch their desi ...

How to assign a value in an HTML element using AngularJS

Currently, I am utilizing Angular JS to iterate through a portion of a scope that is initially a JSON array. My objective is to verify the existence of a specific value in that array. If the value exists, then certain actions should be taken. The code bel ...

What is the best way to notify the user about the input in the textbox?

Imagine you have a button and an input field. How could you notify the user of what is in the input field when the button is pressed? Please provide a simple explanation of your code. ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

End of ImageButton tag

I am currently working on this code : <div runat="server" class="slide"> <img src="images/picto_detail.gif" onclick='<%# Eval("CampagneRappelId","hideshow(\"details{0}\")")%>' /> <div id='details<%# Eval("C ...

Is there a way to organize this array based on the group score?

0: {id: 2575, groepName: "ezeez-1", groupScore: 50, Players: Array(0)} 1: {id: 2574, groepName: "ezeez-2", groupScore: 25, Players: Array(0)} 2: {id: 2576, groepName: "ezeez-3", groupScore: 10, Players: Array(0)} 3: {id: 2577, ...

"Converting an HTML file to a Word file using PHP - a step-by-step

Help needed with converting an HTML file to MS Word using PHP code. Below is the code I am using: include("connection.php"); extract($_REQUEST); ob_start(); include("counties/$county_name/$file"); $html_content = ob_get_contents(); ob_end_clean(); header ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...

Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route. When I try to access the index page, everything seems to be working fine. Howev ...

`Adding data to Rails database and displaying without the need for reloading using AngularJS`

When working on my Rails project, I encountered an issue with adding data to the database using `http.post` from an AngularJS controller. Below is the code snippet demonstrating this: RestaurantIndexCtrl.js.coffee: restauranteur.controller 'Restaura ...

Strategies for launching a website with NPM-managed JavaScript dependencies?

Currently, in the process of building a website with Angular2 and TypeScript, I adhered to the 'Getting started' guide from the official website. However, upon completion, I noticed that my node_modules directory is approximately 70MB in size. Th ...