Swapping values in JSON by comparing specific keys: A guide

I have JSON data that contains a key called reportData with an array of values:

 {"reportData":[
    ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"],
    ["1186","R","5t","R","01","L","TP","00110","1854","2016","FE LL","06W3","01","19065","FB01"],
    ["1187","R","6t","H","06","L","TP","04333","1864","2015","CF FE SL","0209","FD22","19845",null],
    ["1188","R","7t","H","06","L","PR","04041","6951","2015","CC CT FE GN PC","0070","00","36590","LB00"],
    ["1189","R","8t","H","06","L","WS","04290","4450","2014","CF   EN   FE   PC   TP","0070","EA30","28320.00",null],
    ["1190","R","9t","H","06","L","LA","04915","4430","2015","CF DK FE RR TC","0040","10","23680","FB10"],
    ["1191","R","10t","H","06","L","LF","04335","2532","2015","CF FE GE","0040","FC10","22970",null],
    ["1192","R","11t","H","06","L","SA","04772","8345","2015","BZ C8 FE","01D6","13","33390","LC13"]]}

I need to compare and interchange data in each array element, specifically at the 12th and 14th indexes.

For example, in "reportData":[
    ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"]]

This means I want to compare and swap '20' with 'FF20' using the following logic:

If the value at the 14th index is not null, then assign,
   The value at the 12th index = the value at the 14th index.
If the value at the 14th index is null,
then leave the value at the 12th index as it is.

This process needs to be repeated for all arrays in the "reportData" key.

Therefore, my final JSON should look like this,

    "reportData":[
["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","FF20","23840","FF20"],//interchange 12th with 14th if 14th is not null
["1186","R","5t","R","01","L","TP","00110","1854","2016","FE LL","06W3","FB01","19065","FB01"],//interchange 12th with 14th if 14th is not null
["1187","R","6t","H","06","L","TP","04333","1864","2015","CF FE SL","0209","FD22","19845",null],//leave 12th as it is since 14th is null
["1188","R","7t","H","06","L","PR","04041","6951","2015","CC CT FE GN PC","0070","00","36590","LB00"],//interchange 12th with 14th if 14th is not null
["1189","R","8t","H","06","L","WS","04290","4450","2014","CF   EN   FE   PC   TP","0070","EA30","28320.00",null],//leave 12th as it is since 14th is null
["1190","R","9t","H","06","L","LA","04915","4430","2015","CF DK FE RR TC","0040","10","23680","FB10"],//interchange 12th with 14th if 14th is not null
["1191","R","10t","H","06","L","LF","04335","2532","2015","CF FE GE","0040","FC10","22970",null],//leave 12th as it is since 14th is null
["1192","R","11t","H","06","L","SA","04772","8345","2015","BZ C8 FE","01D6","13","33390","LC13"]]//interchange 12th with 14th if 14th is not null

I tried a function but it didn't work as expected. Can anyone help me resolve this issue?

Answer №1

Let's say we have a JSON object called data, in that case

data.reportData.forEach(function(item){
    if(item[14] != null)
        item[12] = item[14];
});

Answer №2

Not quite sure why the array includes FCOL and ICOL in the example function provided, but here's a solution to the problem at hand.

The function is named copyElement instead of swapJsonKeyValues. This is because 1) the data has already been parsed into a JavaScript object and not JSON, and 2) you're not actually swapping key/value pairs, just copying an element based on a condition.

The function simply checks if each array in the object is at least 14 elements long, and if it is, it then checks if the 14th element is not null. If it's not null, then it copies the value to the 12th element. The map function creates a new array with the callback applied to each array in reportData.

function copyElement(obj) {
  return obj.reportData.map(function (el) {
     if (el.length >= 14 && el[14] !== null) el[12] = el[14];
     return el;
  });
}

copyElement(obj);

DEMO

Answer №3

Give this a shot:

let data =  {"reportData":[
    ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"],
    ["1186","R","5t","R","01","L","TP","00110","1854","2016","FE LL","06W3","01","19065","FB01"],
    ["1187","R","6t","H","06","L","TP","04333","1864","2015","CF FE SL","0209","FD22","19845",null],
    ["1188","R","7t","H","06","L","PR","04041","6951","2015","CC CT FE GN PC","0070","00","36590","LB00"],
    ["1189","R","8t","H","06","L","WS","04290","4450","2014","CF   EN   FE   PC   TP","0070","EA30","28320.00",null],
    ["1190","R","9t","H","06","L","LA","04915","4430","2015","CF DK FE RR TC","0040","10","23680","FB10"],
    ["1191","R","10t","H","06","L","LF","04335","2532","2015","CF FE GE","0040","FC10","22970",null],
    ["1192","R","11t","H","06","L","SA","04772","8345","2015","BZ C8 FE","01D6","13","33390","LC13"]]}

data.reportData.map(function (row) {return row[12] = (row[14]) ? row[14] : row[12};)
console.log(data);

The map function will evaluate the conditions specified and provide the necessary result.

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

The initial component update

I am new to React and currently working on a main component that includes a child component with a table. Upon mounting, I make an API request to fetch data which is then displayed in the table. My issue arises when, after the initial update of the child c ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

Troubleshooting a manual installation of the mysql2 package - encountering an

I've encountered an issue while trying to initialize Sequelize in my application. When using docker-compose to build and run the app, I am prompted to manually download the mysql2 package. Despite my attempts to download it using various methods like ...

Import a .txt file into a PHP multi-dimensional array

The given data in .txt format is as follows: 20|Charlotte Aaaa|XXXX*SALE*O9 60|Peggy Bbbbb|XXXX*SALE*O8 25|Ashley Ccccc|XXXX*SALE*O7 103|Andrew Ddddd|XXXX*SALE*O1 51|Sally EEeee|XXXX*SALE*O6 9|Richard Fffff|XXXX*SALE*O3 23|Charlotte Aaaaaaaa|XXXX*SALE*O10 ...

The error message "Unable to push property in an undefined array" is displayed when attempting to push a property into

I'm struggling to debug the error message TypeError: Cannot read property 'push' of undefined. The following code snippet is what's causing the problem: const parent_lead_contact = this.props.parentLeads?.filter((lead) => lead. ...

``There seems to be a problem with the ngb time picker when using the up and

Currently, I am utilizing Bootstrap 4 and NG Bootstrap time picker for a project in Angular 10. Despite correctly adding all the code, I have encountered an issue where the up and down arrows on the time picker are not functioning as expected. Below is a s ...

Utilizing the components within the range set by paper.setStart() and paper.setFinish() in Raphaels

My question has two parts - the first and second part. Let's consider an example code that I am working on. I am creating a map of my country with regions, and I want to perform actions on the entire map such as scaling or translating (as seen in the ...

Struggling to make a JavaScript program that sums up odd numbers

Let's tackle this challenge: Your task is to create a program that adds up all the odd numbers between 1 and the number provided by the user. For instance, if the user inputs 7, the program should calculate 1 + 3 + 5 + 7. The result of this calculati ...

Tips for defining the operational scope of orbit controls in three.js

I've been working on creating an orientation cube in threeJS and have set up 2 scenes with different viewports, cameras, and controls. Check out the fiddle here var controls = new THREE.OrbitControls( view.camera, container.domElement ); In the fid ...

The order of serialization for JsonPropertyName in .NET Core 3's System.Text.Json.Serialization

While I made the transition to .NET Core 3, I decided to switch from using Newtonsoft.Json serialization to System.Text.Json.Serialization. One feature that I particularly liked and want to continue using is the JsonPropertyName attribute. In the previous ...

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

Exploring the Differences Between Arrays of Objects and Arrays in JavaScript

While working on a project for a client, I encountered an interesting problem. I have two arrays - one with objects and one with values. The task is to populate the array of objects with new objects for every item in the value array. To clarify, here is th ...

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

Working with JSON responses from Google search in Python using the Requests library. Utilizing regex for

I need to convert the initial response into a valid JSON format, which I can do but in a somewhat messy way. Here's the original response: // API callback google.search.Search.apiary2387({ "cursor": { "currentPageIndex": 0, "estimatedResultCoun ...

The tooltip chart is not displaying all of its data

I create a dynamic tooltip with a custom chart inside of it. tooltip: { borderRadius: 15, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none', useHTML: true, shared: true, formatter: function() { ...

Tips on sending error messages to an MVC view during an Ajax call

When using ajax to call a controller action method on an MVC button click event, there may be validation logic in the controller that needs to notify the user of any errors. Is there a way to send an error message to the ajax success event from the control ...

Fixing extended properties on an express request can be done by following these steps

I've been working on a JavaScript middleware where I can extract user information using the "req" object in the route handler. When I log currentUser, I get the expected value, but I'm encountering a TypeScript error warning: Property 'curre ...

What is the method for inserting a new <p> tag whenever a user sends a new message in ReactJS?

Whenever I press the Enter key, the content is updated in the same tag. First I sent Hello World! The second time I tried to send Hello as a new message, it was updated within the same tag. I have shared code snippets related to the messaging function ...

Update the router URL without switching pages, yet still record it in the browser history

One of the features on my search page allows users to perform searches and view results. Initially, I faced a challenge in updating the router URL without navigating, but I managed to overcome this by utilizing the "Location" feature. In my ngOnInit meth ...

Controller method remains inaccessible despite multiple attempts with Javascript ajax Get call

I've tried numerous solutions for this issue, but I'm still unable to make it work. My goal is to invoke a controller method that accepts a parameter and returns a string based on that parameter. Despite using an ajax GET request, the outcome is ...