How to add item to each level of a nested array
You could take a recursive approach and hand over an incremented level for each level.
addLevels
takes a level variable and returns a nother function which separates levels
from the object. The rest of the object is a new variable.
The inner function returns a new object with a level
property, the old object without levels
and a property levels
which gets the mapping of the nested arrays.
addLevel
features a closure over level
which keeps the value for the nested function.
const
addLevel = (level = 0) => ({ levels = [], ...o }) =>
({ level, ...o, levels: levels.map(addLevel(level + 1)) }),
data = { name: "Anything2", code: "SS_1", levels: [{ levelName: "New level", levels: [{ levelName: "New Level2", levels: [{ levelName: "New Level2" }, { levelName: "New Level2", levels: [{ levelName: "New level" }] }, { levelName: "New Level2" }, { levelName: "New Level2" }] }, { levelName: "New Level2" }, { levelName: "New Level2", levels: [{ levelName: "New level" }] }] }] },
result = addLevel()(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }