0

I would like to add to the an existing json a new value in the following path:  

VAL:"BS", PATH:["info", "bosses", "lives"]

if my json had the passes it will add the value, otherwise I will create the fields

example:

var myJson = {
    "root": {
        "name": "jim",
        "age": "4",
        "info": {"bosses": {"name": "sam"}}
    }
}

so my new json will look like this:

 var myNewJson = {
    "root": {
        "name": "jim",
        "age": "4",
        "info": {"bosses": {"name": "sam", "lives": "BS"}}
    }
}

an example when I didn't have the fields:

var myJson = {
        "root": {
            "name": "jim",
            "age": "4",
        }
    }

the output:

var myNewJson = {
        "root": {
            "name": "jim",
            "age": "4",
            "info": {"bosses": {"lives": "BS"}}
        }
    }

an example where part of the path exists I didn't have the fields:

var myJson = {
        "root": {
            "name": "jim",
            "age": "4",
          "info": {"salary": 500}
        }
    }

the output:

var myNewJson = {
        "root": {
            "name": "jim",
            "age": "4",
            "info": {"salary": 500, "bosses": {"lives": "BS"}}
        }
    }

how can I check if path exists (note: part of the path might exist- how can I know from where to start it?)

dina
  • 4,039
  • 6
  • 39
  • 67
  • ```if (myJson.root['info']) { /* code */ }``` – webdeb Jun 27 '16 at 11:39
  • See this http://stackoverflow.com/a/13719799/3284355 although they use string like `path='info.bosses.lives"` you can use it like this `assign(myJson, PATH, VAL);` since the path variable can also be array. – Molda Jun 27 '16 at 11:58
  • This could be good, but what if your attribute/field has 0 (zero) value? If you check path.to.your.node it will be false: – Lorenzo Eccher Nov 28 '17 at 09:14

2 Answers2

1

This is old, but... testing existence of fields on paths is nicer now, with optional chaining, like: var infoExists = !!myJson?.root?.info - the ?. means that if root were missing, the line wouldn't break.

In this case though, I wouldn't worry about testing for the existence of fields, I'd use spread operators to just rebuild the info object:

var newInfo = {"bosses": {"lives": "BS"}};
var info = {...myJson.root.info, ...newInfo};

if myJson.root.info doesn't exist, no problem (as long as myJson.root does, cue an optional chaining check?), we just get the newInfo.

if myJson.root.info currently holds {"salary": 500}, the spread operators will combine that to "info":{"salary": 500, "lives": "BS"}.

if myJson.root.info currently holds the same as newInfo, well, no sweat, we end up with no change.

Now you have the info object exactly as you want it, you can simply replace it in the original object with myJson.root.info = ...info;

phedro
  • 121
  • 1
  • 10
0

The first thing you could think it works could be some code like:

if (myObject.attributeName){
    //property exists!
}

It will work for you in many tests but I sure you know that javascript manage some values as truthy or falsy. It use lot's of different type value as boolean false in many comparison (just === not convert type). When you check something as

if(somethingtotest){
// it's true
}

It is the same you'd write

if(somethingtotest == true){
// it's true
}

'==' operator tryes to convert different types to be "similar" together. In the first example code many of object attribute values can be '==' true. That attribute value is truthy, meaning it’s an object, a non-empty string, a non-zero number that’s not NaN, true, and not null or undefined. That means if the attribute is an empty string (“”), this check will fail. The same if value is 0 (zero), null, false. Failing, in this case, doesn’t mean that the property doesn’t exist. In fact, the property does exist and contains a value, but the value is falsy and so doesn’t pass this test.

Since ECMAScript 5 the base Object has the function hasOwnProperty(propertyName) So you could try

if(myObject.hasOwnPorperty('attributeName')){
// do something
}

This function remembers us that the Objects has also prototype attributes that our object could inherit. For example if I write

myObject.anyAttribute='AnyValue';
var my1stObject = Object.create(myObject);
var my2ndObject = Object.create(myObject);
myObject.anyAttribute='AnotherValue';
console.log(my1stObject.anyAttribute);
console.log(my2ndObject.anyAttribute);

last two rows will print 'AnotherAttribute'. In this case 1st and 2nd objects have not own property anyAttribute but they will use the prototipe one. Different if you write

myObject.anyAttribute='AnyValue';
var my1stObject = Object.create(myObject);
var my2ndObject = Object.create(myObject);
my1stObject.anyAttribute='AnotherValue';
console.log(my1stObject.anyAttribute); //AnotherValue
console.log(my2ndObject.anyAttribute); //AnyValue

First object hasOwnProperty 'anyAttribute' because we set it.

At last, to be shure to check if property, proptotipe or own, really exists, you would like to use

if('anyProperty' in myObject){
//do something
}

I suggest you to read it better at this link: https://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

Lorenzo Eccher
  • 301
  • 2
  • 4