-1

I am currently doing this by this method. Need a better implementation for this Scenario: Here is the following:

var testjson = {  
   "key1":"val1",
   "key2":"val2",
   "key3":{  
      "k2":"v2",
      "k3":{  
         "k4":"v4",
         "k5":"v5"
      }
   },
   "haskey": function (base, path) {
        var current = base;
        var components = path.split(".");
        for (var i = 0; i < components.length; i++) {
            if ((typeof current !== "object") || (!current.hasOwnProperty(components[i]))) {
                return false;
            }
            current = current[components[i]];
        }
        return true;
    }
}

console.log( testjson.haskey(testjson,"key3.k3.k4"));
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
sathish
  • 32
  • 9
  • [Here is the Fiddle for Demo](//jsfiddle.net/sathishrazor/k6912yzv) – sathish Oct 09 '17 at 07:16
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – Yury Tarabanko Oct 09 '17 at 07:18
  • I need a prototype method for json objects like obj.hasownproperty("key1") stated above to check the nested keys like obj.haskey(key3.k3.k4) – sathish Oct 09 '17 at 07:21
  • You have object literals not json. JSON is a string representation of javascript objects (you can't pass functions in it at least for now because in general functions are not serializable). Then the question is still not clear. If you want to add a method to `Object.prototype` you could do it but it is considered to be a bad practice. Also as currently written `haskey` doesn't need to be a method at all (you don't use `this` in it) – Yury Tarabanko Oct 09 '17 at 11:40
  • I just wanted to check a nested property exist inside a Json object like ( if json has key1.key2.key3 ) – sathish Oct 09 '17 at 13:29
  • https://stackoverflow.com/questions/20804163/check-if-a-key-exists-inside-a-json-object?rq=1 – sathish Oct 10 '17 at 02:02

1 Answers1

0

First of all Sorry for asking misleading question.I just need a method for checking a nested object Property exists in a JavaScript object or not. There is nothing to do with prototype with this question. I just created a custom method with two argument one for object and another for property to check.This works fine, I came to a conclusion after looking at this ans->Checking if a key exists in a JavaScript object?

Here is my Method to check the property exist or not in an Object

var testobject = {
  "key1": "value",
  "key2": {
    "key3": "value"
  }
}


function checkproperty(object, path) {
  var current = object;
  var components = path.split(".");
  for (var i = 0; i < components.length; i++) {
    if ((typeof current !== "object") || (!current.hasOwnProperty(components[i]))) {
      return false;
    }
    current = current[components[i]];
  }
  return true;
}

console.log(checkproperty(testobject, "key2.key3"))
sathish
  • 32
  • 9