Skip to content

Instantly share code, notes, and snippets.

@thomashibbard
Last active February 28, 2018 03:46
Show Gist options
  • Save thomashibbard/a4b74030e4115c0197b2167b02837e93 to your computer and use it in GitHub Desktop.
Save thomashibbard/a4b74030e4115c0197b2167b02837e93 to your computer and use it in GitHub Desktop.
const addPropToArrayOfObjectsRecursive = (prop, value, array, result = {}) =>
array.reduce((accum, object, index) =>
Object.hasOwnProperty.call(object, 'children') ? [
...accum,
{
...object,
[prop]: value,
children: addPropToArrayOfObjectsRecursive(
prop, value, object.children, accum
)
}
] :
[
...accum,
{
...object,
[prop]: value
}
], result)
const data = [{
name: "apple",
children: [{
name: "apple-child-1",
children: [{
name: "apple-grandchild"
}]
}]
},
{
name: "orange"
}
]
console.log((addPropToArrayOfObjectsRecursive('active', false, data)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment