With a nested object such as the 'root' object below; How can I add a 'dummy' object to those arrays where the length of the array is less than 2.
var root = {
children: [
{
children: [
{value: 42}
]
},
{
children: [
{value: 42},
{value: 42}
]
},
{value: 42}
]
};
An example of an object i want to insert into arrays where array.length < 2
:
var dummy = {value: 10, dummy: 1};
the resulting array:
var rootWithDummies = {
children: [
{
children: [
{value: 42},
{value: 10, dummy: 1}
]
},
{
children: [
{value: 42},
{value: 42}
]
},
{value: 42}
]
};
I am trying to use recursion though I still have much to learn:
EDIT original addDummies function was checking for nest.values
when it should have been nest.children
CORRECTED FUNCTION
function addDummies (nest, dummyObject) {
if (nest.hasOwnProperty("children")) {
if (nest.children.length < 2) {
nest.children.push(dummyObject)
}
nest.children.forEach(function (item) {
addDummies(item);
;})
}
}
OLD INCORRECT FUNCTION function addDummies (nest, dummyObject) {
if (nest.hasOwnProperty("values")) {
if (nest.values.length < 2) {
nest.values.push(dummyObject)
}
nest.values.forEach(function (item) {
addDummies(nest.values);
;})
}
}
this attempt does not seem to call addDummies recursively nor does it have any checking that the value of 'values' is actually an array (and therefore has a length property).