What is the best way to transfer information from an old JSON file to a new JSON file using JavaScript

I have a JSON file and I need to extract the content of "data" where the provider is "AXIS DATA" into a new JSON file. How can this be achieved?

Here's what I've attempted:

First, I convert it using JSON.parse and then search for the desired data with a for loop.

This is the code I have so far:


var searchedResult = {};
var jsonData = JSON.parse( YOUR_JSON_DATA );
for (var i=0; i < jsonData.data.length; i++) {
    if (jsonData.data[i].provider == "AXIS DATA") {
        searchedResult = jsonData.data[i];
    }   
}

However, the result was not as expected. I believe the issue lies within the if() condition but I am unsure about the exact problem.

This is the sample JSON file:

{
    "errNumber": "0",
    "userID": "EKL0003097",
    "data": [
        {
            "code": "BXD1",
            "price": "15000.00",
            "name": "Voucher Axis Aigo 1GB 24J 30H",
            "ep": "770",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "AXIS DATA"
        },
        {
            "code": "BXD2",
            "price": "25000.00",
            "name": "Voucher Axis Aigo 2GB 24J 30H",
            "ep": "660",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "AXIS DATA"
        },
    {
            "code": "BOLT1",
            "price": "31000.00",
            "name": "Bolt Kuota 1,5GB 24Jam 30hr",
            "ep": "1320",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "BOLT"
        },
        {
            "code": "BOLT3",
            "price": "50000.00",
            "name": "Bolt Kuota 3GB 24Jam 30hr",
            "ep": "1127",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "BOLT"
        }
    ],
    "respMessage": "PROSES BERHASIL"
}

The expected output in the new JSON file should be:

{
    "data": [
        {
            "code": "BXD1",
            "price": "15000.00",
            "name": "Voucher Axis Aigo 1GB 24J 30H",
            "ep": "770",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "AXIS DATA"
        },
        {
            "code": "BXD2",
            "price": "25000.00",
            "name": "Voucher Axis Aigo 2GB 24J 30H",
            "ep": "660",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "AXIS DATA"
        }
    ]
}

Answer №1

To insert an empty array into the data property of hasilsearching, and push any matching items onto it:

var hasildata = {"errNumber":"0","userID":"EKL0003097","data":[{"code":"BXD1","price":"15000.00","name":"Voucher Axis Aigo 1GB 24J 30H","ep":"770","isActive":"Active","type":"KUOTA","provider":"AXIS DATA"},{"code":"BXD2","price":"25000.00","name":"Voucher Axis Aigo 2GB 24J 30H","ep":"660","isActive":"Active","type":"KUOTA","provider":"AXIS DATA"},{"code":"BOLT1","price":"31000.00","name":"Bolt Kuota 1,5GB 24Jam 30hr","ep":"1320","isActive":"Active","type":"KUOTA","provider":"BOLT"},{"code":"BOLT3","price":"50000.00","name":"Bolt Kuota 3GB 24Jam 30hr","ep":"1127","isActive":"Active","type":"KUOTA","provider":"BOLT"}],"respMessage":"PROSES BERHASIL"};

var hasilsearching = { data: [] };
for (var i=0 ; i < hasildata.data.length ; i++){
  if (hasildata.data[i].provider == "AXIS DATA") {
    hasilsearching.data.push(hasildata.data[i]);
  }   
}

console.log(hasilsearching);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Another alternative is to use filter for a simpler approach:

var hasildata = {"errNumber":"0","userID":"EKL0003097","data":[{"code":"BXD1","price":"15000.00","name":"Voucher Axis Aigo 1GB 24J 30H","ep":"770","isActive":"Active","type":"KUOTA","provider":"AXIS DATA"},{"code":"BXD2","price":"25000.00","name":"Voucher Axis Aigo 2GB 24J 30H","ep":"660","isActive":"Active","type":"KUOTA","provider":"AXIS DATA"},{"code":"BOLT1","price":"31000.00","name":"Bolt Kuota 1,5GB 24Jam 30hr","ep":"1320","isActive":"Active","type":"KUOTA","provider":"BOLT"},{"code":"BOLT3","price":"50000.00","name":"Bolt Kuota 3GB 24Jam 30hr","ep":"1127","isActive":"Active","type":"KUOTA","provider":"BOLT"}],"respMessage":"PROSES BERHASIL"};

var hasilsearching = { data: hasildata.data.filter(({ provider }) => provider == "AXIS DATA") };

console.log(hasilsearching);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Answer №2

To easily sort through your information, you can use this method:

const sortedInformation = dataArray.filter(item => item.type === 'AXIS DATA');

Answer №3

Utilizing the forEach method

var information={
    "errNumber": "0",
    "userID": "EKL0003097",
    "data": [
        {
            "code": "BXD1",
            "price": "15000.00",
            "name": "Voucher Axis Aigo 1GB 24J 30H",
            "ep": "770",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "AXIS DATA"
        },
        {
            "code": "BXD2",
            "price": "25000.00",
            "name": "Voucher Axis Aigo 2GB 24J 30H",
            "ep": "660",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "AXIS DATA"
        },
    {
            "code": "BOLT1",
            "price": "31000.00",
            "name": "Bolt Kuota 1,5GB 24Jam 30hr",
            "ep": "1320",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "BOLT"
        },
        {
            "code": "BOLT3",
            "price": "50000.00",
            "name": "Bolt Kuota 3GB 24Jam 30hr",
            "ep": "1127",
            "isActive": "Active",
            "type": "KUOTA",
            "provider": "BOLT"
        }
    ],
    "respMessage": "PROSES BERHASIL"
}
var filteredData={data:[]}
information.data.forEach(entry=>{
if(entry.provider=="AXIS DATA")
filteredData.data.push(entry)
})

Answer №4

To populate an array with specific fields, you can implement the following method:

var dataArray = [];
for(var element of jsonData){
  if(element.source === "AXIS DATA"){    
    dataArray.push(JSON.parse(JSON.stringify(element)));
  }
}

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

Apply CodeMirror theme and plugins using an HTML attribute

On my website, I have implemented a CodeMirror text area from . <form><textarea id="code" name="code" codemirror-type='lineNumbers: false, styleActiveLine: true, matchBrackets: true;'>CODE HERE</textarea></form> I added ...

Is there a way to transform this nested json string into a Java object?

Help needed with converting a JSON string in a unique "special" format into a Java object. Struggling to access individual values such as the location or "resolved_at". Tried using GSON and JSONPOBJECT without success. { "result": { "upon_approval ...

experiencing difficulties in retrieving the outcome from a sweetalert2 popup

function confirmation() { swal.fire({ title: "Are you absolutely certain?", text: "You are about to permanently delete important files", type: "warning", showCancelButton: true, show ...

Ways to define global variables with JavaScript

What is the correct way to create a global variable in JavaScript that is available throughout the entire HTML document? Is it possible to access a variable declared in one script from another? ...

How to append double zeros to a number in Material UI Data Grid

I'm currently working on a React.js application that utilizes the DataGrid component from the Material UI (MUI) library to display data. My challenge lies in formatting full numbers with trailing zeroes for better clarity. For example, displaying 625 ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

Seeking assistance to transfer div elements into a different div post an onclick event

I have a container that contains four separate divs. My goal is to append the remaining three divs to another specific div after clicking on one of them. Does anyone know how I can achieve this? <!DOCTYPE html> <html lang="en"> < ...

Ways to remove the highlighting from a selected list item using CSS/Javascript

I have a problem with a list of images and keywords that act as selections for users. When a user clicks on a selection, it highlights the corresponding image using CSS shadow. However, I am trying to figure out how to deactivate this highlight later on, e ...

Utilizing list view formatting to incorporate external URL references from platforms such as Twitter or Instagram

In an attempt to format a list view, I want the image URL stored in the "mediaUrl" column to display as an image. Here is the JSON I am using: { "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/row-formatting.schema.json&quo ...

Tips for managing state updates in React Redux

Currently, I am utilizing a reducer to manage the state in Redux. The current structure of my state is as follows: { activeConversation: "Jim" conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] user: {id: 8, username: &quo ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

Displaying or concealing dropdown menus based on a selected option

My goal is to have a drop-down menu in which selecting an option triggers the display of another drop-down menu. For example, if I have options like "Vancouver," "Singapore," and "New York," selecting Vancouver will reveal a second set of options, while ch ...

Experimenting with the input type generated by the Form Helper tool

Before generating the form using Form Helper, is there a method to preview the type of input it will produce? I would like to confirm whether it will result in a select or multi-select element before loading the page. ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet: const response = await fetch(' ...

Tips for automating the activation of intents at specific scheduled times in Dialogflow

I'm attempting to automatically trigger intents in Dialogflow to obtain the user's contact details at a scheduled time. Is it possible to achieve this using JavaScript? If so, could you please provide the code? ...

Exploring Node and Express Request Query

I'm struggling with a specific endpoint setup in my code. // GET /api/logs/ app.get('/api/logs', function (req, res) { if (req.query.reverse === true) { res.send((mainModule.logs).reverse()); } else { res.send(mainModule.logs) ...

The function '.save' is not recognized by Mongoose

As a newcomer, I have been trying to understand the code in this calendar app that I created using express-generator. Everything seems to be working fine with connecting to MongoDB, but I am facing issues when trying to save a document. The section of my ...