Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting and removing keys with null values

Tags:

javascript

  • How can i remove the key's with null values and form a new json.
  • How can iterate this response.... where i want to display.. this key ==> corresponding value.
like image 660
John Cooper Avatar asked Oct 20 '25 14:10

John Cooper


2 Answers

1: This will remove any falsey value i.e. Null, undefined or empty strings. You could specifically check for nulls though. Make sure you read up and understand what delete does, it gets a lot of people in trouble.

for(var key in someObject) {
    if(!someObject[key]) {
        delete someObject[key];
    }
}

2: You can iterate all properties and values of objects like so:

for(var key in someObject) {
    console.log("The value of " + key + " is " + someObject[key]);
}
like image 125
Tyler Avatar answered Oct 23 '25 03:10

Tyler


For starters fix your javascript object as what you have posted is full of errors. Once you have a valid array:

var values = [{
    'SPO2': 222.00000,
    'VitalGroupID': 1152,
    'Temperature': 36.6666666666667,
    'DateTimeTaken': '/Date(1301494335000-0400)/',
    'UserID': 1,
    'Height': 182.88,
    'UserName': null,
    'BloodPressureDiastolic': 80,
    'Weight': 100909.090909091,
    'TemperatureMethod': 'Oral',
    'Resprate': null,
    'HeartRate': 111,
    'BloodPressurePosition': 'Standing',
    'VitalSite': 'Popliteal',
    'VitalID': 1135,
    'Laterality': 'Right',
    'HeartRateRegularity': 'Regular',
    'HeadCircumference': '',
    'BloodPressureSystolic': 120,
    'CuffSize': 'XL'
}, {
    'SPO2': 100.00000,
    'VitalGroupID': 1113,
    'Temperature': 32.7777777777778,
    'DateTimeTaken': '/Date(1299856980000-0500)/',
    'UserID': 1,
    'Height': 0,
    'UserName': 'Admin',
    'BloodPressureDiastolic': 78,
    'Weight': 49895.1607,
    'TemperatureMethod': '',
    'Resprate': null,
    'HeartRate': null,
    'BloodPressurePosition': 'Sitting',
    'VitalSite': '',
    'VitalID': 1096,
    'Laterality': '',
    'HeartRateRegularity': 'Regular',
    'HeadCircumference': '',
    'BloodPressureSystolic': 120,
    'CuffSize': ''
}];

then you could loop through it:

for (var i = 0; i < values.length; i++) {
    // this will run for each element of the initial array

    for (var propertyName in values[i]) {
        // this will run for each property of the element
        var propertyValue = values[i][propertyName];

        if (propertyValue == null) {
            // if the value is null remove it
            delete values[i][propertyName];
        } else {
            console.log('name: ' + propertyName + ', value: ' + propertyValue);   
        }
    }
}

Demo.

like image 24
Darin Dimitrov Avatar answered Oct 23 '25 05:10

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!