Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep changing values in a JavaScript object

I have an object which contains an unknown number of other objects. Each (sub-)object may contain boolean values as strings and I want to change them to real boolean values. Here's an example object:

var myObj = {
  my1stLevelKey1: "true",
  my1stLevelKey2: "a normal string",
  my1stLevelKey3: {
    my2ndLevelKey1: {
      my3rdLevelKey1: {
        my4thLevelKey1: "true",
        my4thLevelKey2: "false"
      }
    },
    my2ndLevelKey2: {
      my3rdLevelKey2: "FALSE"
    }
  }
}

What I want in the end is this:

var myObj = {
  my1stLevelKey1: true,
  my1stLevelKey2: "a normal string",
  my1stLevelKey3: {
    my2ndLevelKey1: {
      my3rdLevelKey1: {
        my4thLevelKey1: true,
        my4thLevelKey2: false
      }
    },
    my2ndLevelKey2: {
      my3rdLevelKey2: false
    }
  }
}

Important is that the number sub-objects/levels is unknown. How can I do this effectively by either using classic JavaScript or Mootools?

like image 776
Timo Avatar asked May 08 '15 16:05

Timo


People also ask

Can you modify an object in JavaScript?

Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.

How do you change the value of something in JavaScript?

To change the value of an object in an array:Call the findIndex() method to get the index of the specific object. Access the array at the index and change the property's value using dot notation. The value of the object in the array will get updated in place.

What is the most efficient way to deep clone an object in JavaScript?

Using the Json. Among the above mentioned three ways, for an object to be deep cloned, JSON. stringify() and JSON. parse() functions are used. The parse() method accepts a JSON String as a parameter and creates a JavaScript object accordingly.


1 Answers

Recursion is your friend

(function (obj) { // IIFE so you don't pollute your namespace
    // define things you can share to save memory
    var map = Object.create(null);
    map['true'] = true;
    map['false'] = false;
    // the recursive iterator
    function walker(obj) {
        var k,
            has = Object.prototype.hasOwnProperty.bind(obj);
        for (k in obj) if (has(k)) {
            switch (typeof obj[k]) {
                case 'object':
                    walker(obj[k]); break;
                case 'string':
                    if (obj[k].toLowerCase() in map) obj[k] = map[obj[k].toLowerCase()]
            }
        }
    }
    // set it running
    walker(obj);
}(myObj));

The obj[k].toLowerCase() is to make it case-insensitive

like image 67
Paul S. Avatar answered Oct 13 '22 00:10

Paul S.