test
test

Reputation: 2466

Object assign remove some properties then create new object

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;

Upvotes: 0

Views: 793

Answers (1)

Christopher Messer
Christopher Messer

Reputation: 2090

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)

Upvotes: 1

Related Questions