logo
down
shadow

How to remove nested empty objects in JavaScript?


How to remove nested empty objects in JavaScript?

Content Index :

How to remove nested empty objects in JavaScript?
Tag : javascript , By : LucaN
Date : January 11 2021, 03:32 PM

this will help instead of checking for null ( obj[k] != null ) , check for Object.values().length ( or Object.keys().length) :
const stocklevels = {
  coats: {
    browncoat: ["L", "M", "S"]
  },
  neclace: {},
  earrings: {
    diamond: "Y",
    ruby: "Y"
  },
  shoes: {},
  bags: {}
};

let newObj = Object.keys(stocklevels).reduce((acc, curr) => {  
  if(Object.keys(stocklevels[curr]).length > 0)
    acc[curr] = stocklevels[curr]
    
  return acc;
}, {});


console.log(newObj);
const obj ={ 
  a :{
    b :{
      c :{} // won't remove this
    }
  },
  d : {
    x : 'x'
  }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How do you recursively remove nested objects that contain an empty array?


Tag : javascript , By : keird
Date : March 29 2020, 07:55 AM
This might help you You can remove the elements in your response with empty arrays with this code.
It cycles through the top level, looking for any empty arrays and removing them. Any objects it finds, it recurses into to also remove empty arrays in them:
// make sure the ES5 Array.isArray() method exists
if(!Array.isArray) {
  Array.isArray = function (arg) {
    return Object.prototype.toString.call(arg) == '[object Array]';
  };
}

function removeEmptyArrays(data) {
    for (var key in data) {
        var item = data[key];
        // see if this item is an array
        if (Array.isArray(item)) {
            // see if the array is empty
            if (item.length == 0) {
                // remove this item from the parent object
                delete data[key];
            }
        // if this item is an object, then recurse into it 
        // to remove empty arrays in it too
        } else if (typeof item == "object") {
            removeEmptyArrays(item);
        }
    }    
}

var jsonOBJ = {};
jsonOBJ = jQuery.parseJSON(data);
removeEmptyArrays(jsonOBJ);

How do I test if a Javascript object has only empty objects at the last nested level?


Tag : javascript , By : negonicrac
Date : March 29 2020, 07:55 AM
Hope this helps An object is empty if it's, well, an object, and every one of its keys is in turn an empty object.
function empty(o) {

  function isObject()      { return o && o.constructor === Object; }
  function keyEmpty(key)   { return empty(o[key]; }
  function everyKeyEmpty() { return Object.keys(o) . every(keyEmpty); }

  return isObject() && everyKeyEmpty();
}

Remove objects with empty values from array / Javascript


Tag : javascript , By : Munir
Date : March 29 2020, 07:55 AM
To fix the issue you can do I have an array of objects: , IMHO, you are looking for something like this:
var arr = [{id:0, value: 'zero'}, {id:1, value: 'one'}, {id:2, value: ''}];

var filteredArr = arr.filter(obj => obj.value != '')
console.log(filteredArr);
           
 

Remove empty & null values from nested object (ES6) - Clean nested Objects


Tag : javascript , By : Tornike
Date : March 29 2020, 07:55 AM
wish of those help You could take an straight forward approach by iterating the key/value pairs of the object and iterate nested iterable objects first and then delete the unwanted keys.
function clean(object) {
    Object
        .entries(object)
        .forEach(([k, v]) => {
            if (v && typeof v === 'object') {
                clean(v);
            }
            if (v && typeof v === 'object' && !Object.keys(v).length || v === null || v === undefined) {
                if (Array.isArray(object)) {
                    object.splice(k, 1);
                } else {
                    delete object[k];
                }
            }
        });
    return object;
}

var object = { a: "string not empty", b: { c: "string not empty" }, d: { e: false, f: 0, g: true, h: 10 }, i: { j: 0, k: null }, l: { m: null }, n: { o: 1, p: "string (not empty)", q: {} }, r: [{ foo: null }] };

console.log(clean(object));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Remove duplicates from nested map objects javascript


Tag : javascript , By : user169463
Date : March 29 2020, 07:55 AM
Hope that helps The simple way is that create an array in which you push the elements that are printed.And before printing the other check if its present in array or not.
const arr = [];
{
    this.state.rows.map((qc) =>
        qc.BinsByDayByOrchardsQCs.map((qc2) =>
            qc2.BinsByDayByOrchardsQCsDefects.map((qc3) =>
              {!arr.includes(qc3.Defect) && arr.push(qc3.Defect) &&
                (<div className="row table">
                    {qc3.Defect}
                </div>)
              }
            ) 
        )
    )
}
Related Posts Related QUESTIONS :
  • Why do I get log is not defined
  • get the multiple index of the same string
  • How can I iterate over an Array object by using For IN or FOR OF
  • Launch local executable from web browser
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Make web service not accessible by browser?
  • Select DOM elements within template
  • How to customize angular ui-grid row background color?
  • Binding data in two respective $scope in AngularJS, how?
  • react put some props after import class
  • Variable is distributed among same components
  • switch class in jQuery/JavaScript for active/inactive state
  • How To Track Outbound Clicks Using Javascript
  • How to get total seconds elapsed since the beginning of the month?
  • Protractor: Stale element reference at "browser.wait(EC.visibilityOf(confDial), FIFTY_SECONDS);"
  • Access to an array inside an object
  • Reseting an JavaScript Interval with different value?
  • Learning Angular for the first time - version 2 or 4?
  • Rendering RSS feed (XML) in React with jquery, why do object values parsed from the feed seem empty?
  • Node.js xml2js http.request tag matching
  • applying texture to custom plane geometry in Threejs
  • How do I pass an Event as a function parameter in HTML written inside JavaScript variable?
  • Interface of object parameter with default value and default property
  • Does using try / catch rather than `.catch` observable operator with XHR requests reduce performance?
  • In IE11 background colors not working on printing
  • TypeScript interface signature "(): string"
  • Is synchronous XMLHttpRequest supported in Internet Explorer 10 and 11?
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com