navigating through a JSON to find an empty array field

Can someone assist me with the following JSON problem?

{
"loanDetails": [
{
  "vehicleDetail": {
    "RCBookImageReferences": {
      "imagePathReferences": [
        {

        }
      ]
    }
  },
  "chargeDetails": [
    {

    }
  ],
  "commissionDetails": [
    {

    }
  ],
  "disbursementDetails": [
    {

    }
  ]
}

] } In the above JSON, I am looking to iterate through each key and if it's empty, then set the parent as an empty array. The desired output is:

{"loanDetails":[]}

I tried using the code snippet below:

function isEmpty(obj) {
for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
        return false;
}

return true;
}

However, this code did not give me the expected result. I seem to be stuck at this point. Any help will be greatly appreciated.

Answer №1

In the wipedClean function, we take a closer look at an object by iterating through its keys and recursively applying the wipedClean function to any nested objects. If after cleaning an object, it turns out to be empty, we remove the key associated with that object. If the main object itself ends up being empty, we return undefined, prompting the deletion of the property containing this empty object.

function wipedClean(obj) {
    var isVacant = true;
    for (var index in obj) {
        var content = obj[index];
        if (content === null || typeof content !== 'object' || (obj[index] = wipedClean(content))) {
            isVacant = false;
        } else {
            delete obj[index];
        }
    }
    return isVacant ? undefined : obj;
}

>> data = { name: "John", age: 30, address: { city: "New York" }, info: { date: { year: 2023 } } }
>> wipedClean(data)
<< Object {name: "John", age: 30}

Answer №2

To create recursion, two solutions are provided.

Solution 1: Implementing an empty test function

var boolValue = true;
for(var prop in obj) {
    if(obj.hasOwnProperty(prop) && typeof obj[prop] === 'object')
    {
        boolValue = recursiveIsEmpty(obj[prop]);
    }
    else
    {
        return false;
    }
}

return boolValue;

//check and set empty string
recursiveIsEmpty(jsonDataObj['loanDetails']) ? jsonDataObj['loanDetails'] = [] : null;

Solution 2: Utilizing a recursive empty function that clears the parent object

function recursiveIsEmpty(obj) {
    var boolValue = true;
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop) && typeof obj[prop] === 'object')
        {
            boolValue = recursiveIsEmpty(obj[prop]);
            if (boolValue)
            {
                delete obj[prop]; //empty object detected, so remove from parent;
            }
        }
        else
        {
            return false;
        }
    }

    return boolValue; //returns an empty object
}

recursiveIsEmpty(jsonDataObj['loanDetails']); //results in jsonDataObj['loanDetails'] being emptied []

This method determines if an object has properties that are objects. If it does, it drills down into those objects to check their properties. If a non-object property is encountered, return false is triggered, indicating that the object is not empty.

Answer №3

The JSON-string you provided is invalid and needs to be corrected before proceeding. You can utilize a reviver function parameter (refer to the MDN) to eliminate 'empty' arrays based on specific criteria.

To elaborate, the reviver function handles the traversal of all levels within the parsed object. If it returns undefined, the property will be removed from the object. The provided snippet showcases how the reviver function removes properties containing empty arrays or objects.

This demonstration highlights the process:

// Corrected JSON string
var foo = '{"loanDetails": [{"vehicleDetail": {"RCBookImageReferences": '+
          '{"imagePathReferences": [{}]}}, "chargeDetails": [{}],'+
          '"commissionDetails": [{}],"disbursementDetails": [{}]}]}';

// Parsing with reviver parameter
var fooparsed = JSON.parse(foo,
                            function (key, value) { 
                                return (value.length && value.length == 1 && 
                                        value[0] instanceof Object && 
                                        Object.keys(value[0]).length == 0) ||
                                        value instanceof Array && !value.length
                                    ? undefined : value; 
                            }
                );
// Printing the result
Helpers.log2Screen(Object.print(fooparsed));
<script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>

Answer №4

When utilizing Ajax, it is recommended to serialize the JSON array using JavaScript.

When passing data through JSON:

data: "your data",

Instead, use:

data: $(form).serialize(),

This will pass all the keys of the form being submitted.

To view the result, try printing it on the console.

Answer №5

let data = {
  "loanDetails": [{
      "vehicleDetail": {
        "RCBookImageReferences": {
          "imagePathReferences": [{}]
        }
      },
      "chargeDetails": [{}],
      "commissionDetails": [{}],
      "disbursementDetails": [{}]
    },
    {
      "vehicleDetail": {
        "RCBookImageReferences": {
          "imagePathReferences": [{
            "Valid": "Working"
          }]
        }
      },
      "chargeDetails": [{}],
      "commissionDetails": [{}],
      "disbursementDetails": [{}]
    }],
  "Superman": {
    "Name": ""
  },
  "SpiderMan": {
    "Name": "Senthil"
  }
}

function flattenObject(target, opts) {
  let output = {},
    options = opts || {},
    delimiter = options.delimiter || '.'

  function getKey(key, prev) {
    return prev ? prev + delimiter + key : key
  };

  function step(object, prev) {
    Object.keys(object).forEach((key) => {
      let isArray = options.safe && Array.isArray(object[key]),
        type = Object.prototype.toString.call(object[key]),
        isObject = (type === "[object Object]" || type === "[object Array]")

      if (!isArray && isObject) {
        return step(object[key], getKey(key, prev))
      }

      output[getKey(key, prev)] = object[key]
    });
    if (Object.keys(object) == "") {
      if (object instanceof Array) {
        output[prev] = [];
      } else {
        output[prev] = {};
      }
    }
  };
  step(target)
  return output
};

function unflattenObject(target, opts) {
  let options = opts || {},
    delimiter = options.delimiter || '.',
    result = {}

  if (Object.prototype.toString.call(target) !== '[object Object]') {
    return target
  }

  function getKeyValue(key) {
    let parsedKey = parseInt(key)
    return (isNaN(parsedKey) ? key : parsedKey)
  };

  Object.keys(target).forEach((key) => {
    let splitKey = key.split(delimiter),
      firstPart, secondPart, recipient = result

    firstPart = getKeyValue(splitKey.shift())
    secondPart = getKeyValue(splitKey[0])

    while (secondPart !== undefined) {
      if (recipient[firstPart] === undefined) {
        recipient[firstPart] = ((typeof secondPart === 'number') ? [] : {})
      }

      recipient = recipient[firstPart]
      if (splitKey.length > 0) {
        firstPart = getKeyValue(splitKey.shift())
        secondPart = getKeyValue(splitKey[0])
      }
    }

    // unflatten again for messy objects
    recipient[firstPart] = unflattenObject(target[key])
  });

  // Check for arrays
  let keysArray = Object.keys(result);
  if (keysArray.length > 0 && keysArray[0] === "0") {
    let outputArr = [];
    keysArray.forEach((arrKey) => {
      outputArr.push(result[arrKey])
    });
    return outputArr;
  }
  return result
};

let flattenedData = flattenObject(data);
let dataKeys = Object.keys(flattenedData);
dataKeys.forEach((key) => {
  if (JSON.stringify(flattenedData[key]) === "{}" || JSON.stringify(flattenedData[key]) == "") {
    delete flattenedData[key];
    let pathsArr = key.split(".");
    if (pathsArr.length >= 2) {
      let intVal = parseInt(pathsArr[1])
      if (isNaN(intVal)) {
        key = pathsArr[0];
        flattenedData[key] = {};
      } else {
        key = pathsArr[0] + "." + intVal;
        flattenedData[key] = {};
      }
      let newKeysArr = Object.keys(flattenedData);
      for (var j = 0; j < newKeysArr.length; j++) {
        let tempKey = newKeysArr[j];
        if (tempKey.indexOf(key) != -1 && tempKey.length > key.length) {
          delete flattenedData[key];
        }
      }
    }
  }
})
console.log(flattenedData)
let finalResult = unflattenObject(flattenedData);
alert(JSON.stringify(finalResult))

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

Mastering the art of properly connecting Angular HttpPromise

Recently, I encountered an angular Service containing a crucial function: service.getItemByID = function(id) { var hp = $http({method: "GET", url: "service/open/item/id", headers: {"token": $rootScope.user.token}, para ...

The greedy behavior of jquery UI is not behaving as expected

In my current project, I am attempting to place a diamond-shaped item into a droppable area which then generates two sub-droppables for additional items. However, I am facing difficulty implementing the "greedy" function with the newly generated droppables ...

Error Alert: Duplicate Status Detected While Posting on Twitter via API

I am delving into the world of JavaScript for the first time and using Node.js in conjunction with the Twitter API to enhance my coding skills. To facilitate this learning process, I have incorporated the Twit NPM package into my project. My goal is to dev ...

Utilizing Vue's computed function to filter values from a JSON dataset

How do I efficiently filter an array of JSON data? Here is the code snippet: <div v-if="vacciCounter"> <b-card no-body class="mb-2" v-for="(stateObject, state) in filteredList" v-bind:key="state"& ...

Arrange information according to MLA names

Greetings! I would like to discuss the following Json Data: Is there a way to display only the MLA names list on the UI and determine which MLA has received the most votes? I need assistance in achieving this. Your help is greatly appreciated. Thank you ...

Load data from a MySQL Database into a DataTable

I am currently in the process of developing a CRUD application. With a large dataset stored in a MySQL database, my intention is to utilize a JQuery DataTable instead of manually creating a table. However, the issue I am facing is that while the table appe ...

What is the process for calling app.vue methods from an ES6 module?

I am currently in the process of constructing a vuejs application using webpack, vuex, and vue-router. The organization of my project is as follows: [components] BlockingLayer.vue [store] index.js [restapi] index.js App.vue main.js Within App. ...

How can I implement select2 4.0 AJAX pre-filling?

I have already gone through this, this, this and based on the documentation the key information here, but none of them seem to be working for me. I am attempting to utilize AJAX select2. My goal is to create a generic "select" item. For all elements that ...

What is the best way to ensure a table is responsive while maintaining a fixed header? This would involve the table scrolling when it reaches the maximum viewpoint, while also keeping

Can anyone help me create a responsive table with a fixed header that scrolls when it reaches the maximum viewpoint without scrolling the entire page? I've tried using box-sizing: border-box; and overflow-x:scroll; but it didn't work. Any suggest ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

Analyzing JSON data and creating a tailor-made array

My Dilemma { "rowId": "1", "product_name": [ "Item A", "Item B", "Item C", "Item D", "Item E" ], "product_tag": [ "123456", "234567", "345678", "456789", "5678 ...

Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend: Here is the request code I am using: function confirm() { cons ...

Tips for creating visually appealing text on a web browser with the help of open-source libraries

Have you ever noticed that no matter how we display text on webpages, whether it's in a <p> tag or an <h1> tag, the result is always the same? (a screenshot of a rendering done in Firefox) Do you struggle with pixelated areas on the curv ...

What could be causing the inability to move down on this page?

Trying to scroll down a page using Selenium with Python and the execute_script command, but encountering issues. Despite executing the code provided below, I am unable to reach the bottom of the page: def create_browser(first_page=None): print "Starti ...

Any property modified by an event handler will consistently appear in its original form

Every second, a simple function is called using setInterval, with the goal of determining mouse or keyboard activity. The variable that tracks the activity is updated, but it always remains set to 0 despite the fact that console.log statements are being e ...

It is more beneficial to utilize jQuery instead of directly accessing form element values using document.formname

Just a quick question. Currently, I am working on some JavaScript for pre or frontend validation. I have a question about which line of code is more effective. I usually use this method: document.formname.forminput.value Instead of: $(& ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

JSON File in a Hive Shell

I am seeking assistance with parsing a JSON file using HIVE. The file contains nested arrays, and when attempting to parse it or query it using the HiVE UDF, I could only drill down to one level. The next level arrays were showing up as Null in my results. ...

Exploring PostgreSQL Nested JSON Queries

In my PostgreSQL database version 9.3.4, I have a column of type JSON named "person" with data stored in the following format: {dogs: [{breed: <>, name: <>}, {breed: <>, name: <>}]}. My goal is to extract the breed of the dog at ind ...

My GraphQL Query is throwing a JSON error when using the curlopt_postfields option. What could be causing this

I'm having some trouble with my code and I keep encountering this error message. Any ideas on what might be causing this issue? I believe I've properly escaped all the quotations. {"errors":[{"message":"json body could ...