Utilize JavaScript to encapsulate specific data into a JSON array

I need help converting a string value into JSON format:

hello|world|this|is|javascript || my|name|is|mahdi

My current code successfully splits the string using ||, but I am unable to group the split values into separate arrays in the JSON output. Here is the current result of my code:

{
    "FILEDS": [
        {
            "template_id": "123",
            "fields_id": "456"
        },
        {
            "item": "hello"
        },
        {
            "item": "world"
        },
        {
            "item": "this"
        },
        {
            "item": "is"
        },
        {
            "item": "javascript "
        },
        {
            "item": " my"
        },
        {
            "item": "name"
        },
        {
            "item": "is"
        },
        {
            "item": "mahdi"
        }
    ]
}

However, I would like the output to have separate arrays for the split values like this:

{
    "FILEDS": [
        {
            "template_id": "123",
            "fields_id": "456"
        },
        [
            {
                "item": "hello"
            },
            {
                "item": "world"
            },
            {
                "item": "this"
            },
            {
                "item": "is"
            },
            {
                "item": "javascript "
            }
        ],
        [
            {
                "item": " my"
            },
            {
                "item": "name"
            },
            {
                "item": "is"
            },
            {
                "item": "mahdi"
            }
        ]
    ]
}

Here is a snippet of my code where I split the data and create the JSON array:

<script type="text/javascript" language="JavaScript">

    var data = "hello|world|this|is|javascript || my|name|is|mahdi";
    var templates = {
        FILEDS: []
    };

    templates.FILEDS.push({
        "template_id": "123",
        "fields_id": "456",
    });

    var split_data = data.split("||");

    for (var i = 0; i < split_data.length; i++) {
        var fields = split_data[i].split("|");
        for (var j = 0; j < fields.length; j++) {
            templates.FILEDS.push({
                "item": fields[j],
            });
        }
    }
    console.log(JSON.stringify(templates));
</script>

Answer №1

Give this a try:

let dataSplit = data.split("||");

for (let i = 0; i < dataSplit.length; i++) {
    let sentence = [];
    let fields = dataSplit[i].split("|");
    for (let j = 0; j < fields.length; j++) {
        sentence.push({
            "item": fields[j],
        });
    }
    templates.SECTIONS.push(sentence)
}

Answer №2

You will require an additional array to store the information.

var data = "hey|universe|coding|is|fun || my|alias|is|mia";
var templates = {
    FIELDS: []
};

templates.FIELDS.push({
    "template_id": "123",
    "fields_id": "456",
});

var split_data = data.split("||");

for (var i = 0; i < split_data.length; i++) {
    var fields = split_data[i].split("|");
    var arr = [];
    for (var j = 0; j < fields.length; j++) {
        arr.push({ "item" : fields[j] });
    }
    templates.FIELDS.push(arr);
}
console.log(JSON.stringify(templates));
// result" {"FIELDS":[{"template_id":"123","fields_id":"456"},[{"item":"hey"},{"item":"universe"},{"item":"coding"},{"item":"is"},{"item":"fun"}],[{"item":" my"},{"item":"alias"},{"item":"is"},{"item":"mia"}]]}

Answer №3

Here is another variation using Array.map

[].push.apply(templates.FILEDS, data.split("||").map(function(el){
    return el.split('|').map(function(item){
        return { "item" : item };
    })
}));

UPDATE: if you prefer objects like

{ "FILEDS": [ 
    { "template_id": "123", "fields_id": "456" }, 
    {"items": [
        ["hello", "world", "this", "is", "javascript"], 
        ["my", "name", "is", "mahdi"] 
    ] }
]}

You can make a slight modification to the code above

templates.FILEDS.push({
    "item": data.split("||").map(function(el){
                 return el.split('|');
             })
    }
);

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

Organizing and sifting through JSON files housed in Redis

Considering a switch from MongoDB to Redis for a highly updated JSON data store, with around 50,000 updates per second and potential for up to a million records. Currently, clients are using MongoDB's query language for result sorting and filtering, ...

Merge corresponding elements from two arrays based on their indices

If I have two arrays of objects structured like this: var arr1 = [{name: 'Jay'}, {name: 'Bob'}]; var arr2 = [{age: 22}, {age: 30}]; I am looking to merge them into a combined array as follows: var arr3 = [{name: 'jay', age: ...

Is it time to consider using a Promise in my JavaScript code given its rapid pace of execution?

I want to enhance the user experience of my web app by making elements fade away before being removed. However, I am facing an issue where my code is executing too quickly. I need it to wait for the element to "disappear" before actually removing it. Shoul ...

Learn how to incorporate latitude and longitude coding into PHP to display a map icon that correctly redirects to the desired URL when clicked

I am in need of a table that includes buttons for adding, editing, deleting, and mapping. Everything works fine so far, but when I click on the map button, it should take me to Google Maps with coordinates linked from a MySQL database containing latitude ...

jQuery fade in problem or alternate solutions

When I send a post request to a file and input the response into id='balance', I would like it to have a flickering effect or fadeIn animation to alert the user that it is being updated in real time. I attempted to use the fadeIn() method but it ...

using mongoose to fetch information and storing it in an array

I am getting an undefined return. What is the best way to store the retrieved data in an array? function storeUsers(place) { if (place === 'France') { myModel.find({}, (err, result) => { var userArray = []; ...

Emphasize the close button within the popup window as soon as it appears

One of my coding challenges involves a div element, shown below: <div id="modal" tabindex="-1" ng-show="booleanvariable"></div> When the value of ng-show is true, this div is displayed. A "close" button located under the div should be focused ...

How can I prevent event propagation in Vuetify's v-switch component?

Currently, I am working with Vuetify and have incorporated the use of v-data-table. Whenever I click on a row within this data table, a corresponding dialog box represented by v-dialog should open. Additionally, each row contains a v-switch element. Howeve ...

Code executing twice instead of once in Javascript

Having trouble with a script in my demo below. When I enter "first input", submit, then click on the returned "first input", it alerts once as intended. However, upon refresh, if I enter "first input", submit, then add "second input", submit, and finally c ...

Adjusting Timeout for Specific HTTP Endpoint in NestJS

I recently delved into learning NestJS and I'm curious about how to adjust the response timeout for specific endpoints. One way is to set it on a server level like this: const server = await app.listen(...); server.setTimeout(1800000) Alternativ ...

How can we enhance Backbone.sync() at the Model level to include additional parameters?

Currently, I am facing a challenge with overriding Backbone's sync() method for a Model. I have the function signature set up and it is triggered correctly, but I am unsure about what needs to be included in the function body in order for it to automa ...

What steps can I take to avoid random divs from overlapping on smaller screens when dealing with elements created in the created() hook?

I encountered an issue with the code I'm working on (the circles overlap in the fiddle provided, but display correctly on my PC - possibly due to pixel discrepancies in the fiddle). You can find the code here. TestCircle.vue: <template> <d ...

Locate any identical values within an array and store them in a temporary array

Similar Question: Java Array, Finding Duplicates arr=[3,4,1,2,1,5,2] Is there a way to identify and return the duplicates in this array? The desired output for this example is result [1,2] I am currently working with Java. ...

Creating fresh CSS by extracting essential selectors from an existing CSS file using Javascript

Is there a method to develop a mini JavaScript function that can parse an HTML document, extract specific selectors from a lengthy CSS file that contains over 2000 lines, and create a new CSS file with only the necessary styles? ...

Troubleshooting problems with saving server data to core data in a background thread

Dealing with concurrency can be quite a headache. I've read numerous articles on how to parse and save server data to Core Data, but many tutorials out there are quite basic and don't address the issue of threading. However, when developing an ap ...

Sending an HTTP Post Request in Swift using dataUsingEncoding may corrupt the string

I am currently collaborating on an App with a colleague who posed this inquiry: Post request always wrapped by optional text. He is handling the iOS development, while I'm working on the Android side. The challenge lies in my lack of familiarity with ...

Incorporating a static image file into a Material UI cardMedia component within a Next.js project

I am struggling to insert a static image into Material UI CardMedia component. I have tried the following code: const useStyles = makeStyles((theme) => ({ media: { height: 0, paddingTop: "56.25%", // 16:9 }, })); <CardMed ...

Having difficulties with JavaScript in Rails 4, receiving the error message: "undefined is not a function"

I have been using the gem chosen-rails (or chosen-sass-bootstrap-rails) in my Rails application. In my gemfile, I included the following line: gem 'chosen-sass-bootstrap-rails' Previously, everything was functioning correctly, but now I am enco ...

I'm experiencing difficulties with JS on my website. Details are provided below – any suggestions on how to resolve this issue

Can someone help me with a web project issue I'm facing? Everything was going smoothly until I tried to add some JS for dynamic functionality. However, when I attempt to access my elements by tag name, ID, or class, they always return null or undefine ...

The script fails to execute on content loaded through AJAX in Django

I have a website with nested div elements that make up a complete set. These elements can be dynamically loaded when the user clicks the "load more" button. The website includes a script that changes the style of the aforementioned div element when the pa ...