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

Is there a way to configure MaterialUI XGrid filters to target and filter by the renderCell parameters instead of the backend data source?

While utilizing MaterialUI XGrid to showcase rows of information, I am facing an issue with filtering. Currently, filtering can only be done based on the backend row values rather than what is displayed in the cell. For instance, consider a column named U ...

Use a for loop to fill an array with values and then showcase its contents

I have been trying to figure out how to populate an array and display it immediately when targeting the route in my NodeJS project. Currently, I am able to console log a list of objects. However, I want to populate an array and show it when accessing loca ...

executing the following event in Node.js

Is it feasible to execute only a portion of the code on each iteration of the event loop in an application where requests can take a second or two? Consider the following scenario: function foo() { ...critical code... ...start processing the next ...

What are the steps to retrieve information from your personal server using Astro?

I have successfully set up a NodeJS server using Express and Astro for the frontend, with SSR configured through the Astro adapter for NodeJS. My current challenge is fetching data from the backend, and I am unsure of the correct approach to do so. Below ...

If the given response `resp` can be parsed as JSON, then the function `$

I was using this script to check if the server's response data is in JSON format: try { json = $.parseJSON(resp); } catch (error) { json = null; } if (json) { // } else { // } However, I noticed that it returns true when 'res ...

Utilize React-markdown to interpret subscript text in markdown format

I tried to create subscript text in an .md file using the following syntax: x_i x~i~ Unfortunately, react-markdown did not interpret this as subscript. After some research, I discovered the package remark-sub-super and implemented it with the plugin ...

Returning to the initial state after clicking on an element within a repeated set in AngularJS?

I'm currently facing a challenge, mainly due to my lack of understanding in basic AngularJs concepts. The issue arises when I interact with a list of clickable words. When I click on any of these words, their color changes individually thanks to the i ...

Encountering an issue with using third-party APIs due to receiving an error message stating that the requested resource does not have the 'Access-Control-Allow-Origin' header

My current challenge involves attempting to access a third-party API using AngularJS. Interestingly, I only encounter this issue in Chrome, as it works perfectly fine in IE. The error message that pops up reads as follows: XMLHttpRequest cannot load https ...

Is it necessary to use JS/JQ to trigger PHP form data?

Can PHP files/functions be executed without reloading the page? It can be quite disruptive when developing a chat app and every time you send a message, the entire page refreshes. I attempted to use AJAX but it didn't work. Is it not possible to send ...

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

Sharing information among v-for divisions - Vue.js

I am currently delving into the world of VueJS. While my code may not be the most elegant, it does the job almost as intended. The issue I am facing is that the API provides the title and href separately in different v-for loops, even though each loop only ...

Configure WebStorm so that node_modules is set as the library root, while simultaneously excluding it from indexing

Can WebStorm projects be configured to set the node_modules as the library root, while also excluding it from indexing? I thought I saw a project that had node_modules marked as both library root and excluded, but I'm unsure how to do this. Does anyo ...

PHP fails to retrieve data from a JavaScript Ajax function using the FormData object (specifically, when

I'm facing an issue where my file is not being detected when I send a FormData object using AJAX and PHP code. Both the `$_FILES` array and the `$_POST` array appear to be empty. However, the browser does send the file with the AJAX request. <inpu ...

Using PHP and Laravel to Convert a VARCHAR Value to FLOAT in a Database Query

Within my table, I have stored two fields lat and long, both with the datatype of VARCHAR Now, in Laravel, I am working with the following variables: $ne_lat = 21.405122657695813; $ne_lng = -102.32061363281252; $sw_lat = 19.984311565790197; $sw_lng = -10 ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Encountering a syntax error while attempting to import modules from amCharts

Recently, I have been attempting to incorporate amcharts into my project using npm. After running the command npm install@amcharts/amcharts4, I noticed that all the necessary modules were now present in my node_modules folder and package.json file. Specifi ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...