I am attempting to create an object from JSON.
Part of my object looks like
a: {
name: "A name",
b: {
c: {
d: []
}
}
}
To save bandwidth, empty arrays and empty objects are stripped from the JSON, so the JSON that I receive is
{ "a": { "name": "A name" }}
If I just convert the JSON to an object, this leads to errors when I try to do things like a.b.c.d.length, as undefined does not have a length.
At the moment, I am populating the missing fields by something like
const json = getJson();
const obj = {
...json,
a: {
...json.a,
b: {
...json.a.b,
c: {
...json.a.b.c,
d: json.a.b.c.d || []
}
}
}
};
This is pretty verbose, and is going to get even uglier when there are several fields that need default values.
One obvious solution is to not strip out the empty arrays from the transmitted JSON. Assuming that that is not possible, is there a better way to handle this case?
In the real case, there are multiple fields at each level, so all of the spread operators are necessary. (Even if they were not, I would want to include them as the structure is likely to grow in the future.)
Edit: I am not using JQuery. I am using whatwg-fetch to retrieve data.
$.extend({a:{b:{c:'hello'}}}, {a:{d:{e:'goodbye'}}}), asker would hope for{a:{b{c:'hello'},d:{e:'goodbye'}}}, but actually just gets{a:{d:{e:'goodbye'}}}Edit my mistake, forgot about the optional first argumentdeep. This would work:$.extend(true, {a:{b:{c:'hello'}}}, {a:{d:{e:'goodbye'}}})