Let's I have next javascript object. Now I want clone it but without some fields. For example I want cloned object without field "lastName"
and "cars.age"
Input
{
"firstName":"Fred",
"lastName":"McDonald",
"cars":[
{
"type":"mersedes",
"age":5
},
{
"model":"bmw",
"age":10
}
]
}
Output (cloned)
{
"firstName":"Fred",
"cars":[
{
"model":"mersedes"
},
{
"model":"bmw"
}
]
}
I can do something like
var human = myJson
var clone = $.extend(true, {}, human)
delete clone.lastName
_.each(clone.cars, function(car))
{
delete car.age
}
Do you know easier solution?
If you don't mind adding to object prototypes, this is an easy solution. You may want to modify it some for your own use.
Then when you have an object like:
You can do magic like this.
Or even magic like this!
Here is a standalone function depending on lodash/underscore that i've written that does the same.
It calls a callback for each (value, indexOrKey) pair in the object or array and if true will omit that pair in the resulting object.
The callback is called after the value has been visited so you can omit a whole sub-tree of values that match your condition.
Some samples