0

Trying to remove unnecessary properties from object:

{
    "1502134857307": {
        "bio": "",
        "category": {
            "category1": true
        },
        "name": "dog",
        "snapchat": "",
        "twitter": ""
    },
    "1502134908057": {
        ...
    }
}

I wanted to make it look like this:

{
    "1502134857307": {
        "category": {
            "category1": true
        },
        "name": "dog"
    },
    "1502134908057": {
        ...
    }
}

I have tried: not working

var newObejct = Object.assign({}, $r.props.data);
delete newObejct.bio;
test
  • 2,429
  • 15
  • 44
  • 81
  • 1
    Possible duplicate of [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – Zackary Murphy Aug 11 '17 at 15:49
  • 4
    Not that this is your actual code, but just in case - `new` is a reserved word in JS and should not be used for variable names – Rob M. Aug 11 '17 at 15:50
  • @zackary murphy whats your point? – Jonas Wilms Aug 11 '17 at 15:51
  • removed `new` changed to `newObejct` – test Aug 11 '17 at 15:54
  • What exactly is `$r.props.data` ? Is it the full object shown? If so you need to iterate the nested objects where `bio` is a property, not the outer object – charlietfl Aug 11 '17 at 16:14

1 Answers1

1

Here, try this. Depending on what you want to accomplish, this will iterate through a nested object recursively and remove any property that is an empty string. Feel free to modify the condition to remove whatever else you don't want in your Object.

let clutteredObj = {
    "1502134857307": {
        "bio": "",
        "category": {
            "category1": true
        },
        "name": "dog",
        "snapchat": "",
        "twitter": ""
    },
    "1502134908057": {
        "bio": "",
        "category": {
            "category1": true
        },
        "name": "dog",
        "snapchat": "",
        "twitter": ""
    }
}

function clearEmptyStrings(obj) {
  Object.keys(obj).forEach(key => {
    if (typeof obj[key] === 'object') {
      return clearEmptyStrings(obj[key])
    }
    if (obj[key] === "") {
      delete obj[key]
    }
  })
}

clearEmptyStrings(clutteredObj);

console.log(clutteredObj)
Christopher Messer
  • 2,040
  • 9
  • 13