user2948105 user2948105 - 1 month ago 7
Javascript Question

javascript remove only value but remain the key

I have a json object

var myObj = {'test' : {'key1' : 'value', 'key2': 'value', 'key3': 'value'}}


How can I run a loop to only remove the value but remain the key
so that I get this

var myObj = {'test' : {'key1' : '', 'key2': '', 'key3': ''}}


Or how can i make a copy of the Object without the value??

Answer

You can loop through properties of a javascript object like this:

for (var prop in myObj) {
    if (myObj.hasOwnProperty(prop) &&
        typeof myObj[prop] !== 'function') {

        myObj[prop] = '';
    }
}

Quick rundown of what this does and why:

  • for (var prop in myObj) will go over every property in your object.
  • if (myObj.hasOwnProperty(prop) will make sure you don't change properties inherited through the prototype chain (we don't usually want to do that).
  • && typeof myObj[prop] !== 'function') will ignore any property that is a function. If you do want to change the value of functions on your object, this check should be removed.
  • myObj[prop] = '' assigns a new value to the property (an empty string, in this case).

To do this check "in depth" (multiple levels deep), you would have to call this recursively:

var myObj = {
  'test': {
    'key1': 'value',
    'key2': 'value',
    'key3': 'value',
    'key4': { 'subkey1': 'value', 'subkey2': 'value' }
  }
}

var replaceProps = function(obj, replaceWith) {
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop) && typeof obj[prop] !== 'function') {

      if (typeof obj[prop] === 'object') {
        replaceProps(obj[prop], replaceWith)
      } else {
        obj[prop] = replaceWith;
      }
    }
  }
}

replaceProps(myObj, '');

console.log(myObj);