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

Text alignment issue in Material UI Data Grid Component

Currently, I am working with a DataGrid component nested inside a div that is enclosed within a Box component. I am facing issues in centering the content of the DataGrid and styling the header text. The code snippet I'm using is: Blockquote <B ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

What is the recommended approach for utilizing props versus global state within your components when working with JS Frameworks such as Vue?

Currently, I am delving into a larger project using Vue and I find myself contemplating the best practices when it comes to utilizing props versus global Vuex states for accessing data within a component. To elaborate, let's say I have a component re ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Trying to set headers in Node/Express after they have already been sent is causing an error

I am attempting to send form data from the client side using jQuery to a POST route that will then pass the data to an API in Node/Express. I am encountering an issue where I receive the error message "Can't set headers after they are sent" and I am ...

Receive dual responses in a single express post

I have a question regarding making multiple requests in one post in Express and receiving multiple responses on the client side (specifically Angular). When I try to make two res.send(body) calls, I encounter an error stating: Error: Can't set headers ...

Managing state arrays in React JS: A guide to efficiently adding and removing items using a single function

Using React JS Class Component. Within a single function, I am attempting to... Add an integer value to an array if it is not already in the array and also remove a value from the array if it does exist. Note that initially the array will be empty [] My ...

Preventing the detection of a jshint "error"

When creating an object using the constructor X, I later add multiple methods in the file using X.prototype.method = function () {...}. Although technically an assignment statement, it behaves like a function declaration, which typically doesn't requi ...

Issue: Unable to locate module 'js-yaml' while executing npm start command

Unable to locate module 'js-yaml' Require stack: D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\loaders.js D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\createExplore ...

The CSS and Javascript files are failing to load

My web page is not displaying my CSS and JavaScript properly when I access it through a folder in the browser. Both files are located within multiple subfolders. I have attempted to rename the files to troubleshoot the issue. <head> <link rel=" ...

Exploring numerical elements in interactive content

Struggling with the Wikipedia API and encountering issues with the results that are returned. {"query":{ "pages":{ "48636":{ "pageid":48636, Concerned about how to access a specific ID (such as 48636) without knowing it in advance ...

Instructions for adding the more-vert icon from material-ui into a react project

I've been searching tirelessly, but I can't seem to locate it. Where exactly is the location of this in material-ui? I've seen others using it. Any assistance would be greatly appreciated. My initial thought was: import MoreVertIcon from & ...

Use an Ajax call to "POST" and fetch the Jade layout for rendering

So, I have my own custom AJAX function. export function dynamicURL(obj) { $.ajax({ url: obj.url, type: 'post', data: obj.jade, dataType: 'JSON' }).done(function (ajaxReturn) { console.lo ...

Merge the xAxis functionality with Highcharts

My issue involves a chart generated by highcharts.js. The problem arises with a line chart consisting of 5 values (5 points), each displayed on the xAxis as follows: from value 1 to value 2: 0, 0.25, 0.5, 0.75, 1. I am looking to modify this display and re ...

Manage over 200 checkboxes by storing them in the state

I am facing an issue with managing checkboxes within a table in my application. The table fetches user data and renders each row as its own component, with each row containing a checkbox. The goal is to enable the users to select checkboxes and retrieve t ...

Partial data is being received from the Ajax call

I currently have a textarea and a button on my webpage <textarea id="xxx" class="myTextArea" name="Text1" cols="40" rows="15">@ViewData["translation"]</textarea> <input type="button" id="convert-btn" class="btn btn-primary" value="Convert t ...

pythonAppending new rows to an empty 2D numpy array

Is there a way to populate an empty 2D numpy array with rows using a loop? yi_list_for_M =np.array([]) M =[] for x in range(6) : #some code yi_m = np.array([y1_m,y2_m]) yi_list_for_M = np.append(yi_list_for_M,yi_m) The current output is: [0. ...

Confirming if a JSON is valid in the C programming language

After hours of searching on Google, I am eager to find a way to programmatically verify if the string provided below is valid JSON using C. Is there any solution available? (I am currently relying on the json-c library.) char * jsonString = "{ ...

Retrieve the number of days, hours, and minutes from a given

Is it possible to use JavaScript (jQuery) to calculate the number of days, hours, and minutes left before a specific future date? For example, if I have a timestamp of 1457136000000, how can I determine the amount of time remaining in terms of days, hours ...

The dynamic rendering of datasets is not supported in Material UI's <TableCell> component

I'm currently working on a table component that dynamically renders an item list based on a dataset. The Table component is made up of <TableHead/> and <TableBody/>. I am using the .map() method to dynamically assign values to the <Tabl ...