If I have an array of arrays, each consisting of object property names (strings), how can I recursively modify an object to check whether or not the property exists and add it accordingly. The last value in the array would be applied as a string value of the given property.
const propsToAdd = [
['propA', 'value'],
['propB', 'propC', 'propD', 'value'],
['propB', 'propF', 'value']
];
The resulting object would contain the relevant properties (nested accordingly) and the value of the final property would be equal to the last item in the array.
const resultingObj = {
propA: 'value',
propB: {
propC: {
propD: 'value'
}
propF: 'value'
}
};
I would like to create such an object recursively, as the array will be of unknown length, as will the sub arrays.
It's important to note that the following will not occur and does not need be accommodated.
const propsToAdd = [
['propA', 'value'],
['propA', 'value', 'value1']
];
Put otherwise, value (as a child of propA) cannot both be a property and a value name.
How can I write a recursive function that adds (and nests) key/value pairs to an object?
Since your use of const suggests ES2015, you can make use of arrow functions, destructuring assignment, and default parameters:
const nest = ([x, ...xs], o={}) =>
xs.length === 0 ? x : (o[x] = nest(xs,o[x]), o);
const nestmany = ([xs, ...yss], o={}) =>
xs === undefined ? o : nestmany(yss, nest(xs,o));
const propsToAdd = [
['propA', 'value1'],
['propB', 'propC', 'propD', 'value2'],
['propB', 'propF', 'value3']
];
console.log(nestmany(propsToAdd));
createRec recursively creates the object in a nested form.
function processInput(propsToAdd) {
var resultingObj = {},
propArr;
for (var i = 0, len = propsToAdd.length; i < len; i += 1) {
propArr = propsToAdd[i];
createRec(propArr, resultingObj);
}
return resultingObj;
}
function createRec(propArr, resultingObj, index) {
var prop,
value_Str = 'value';
for (var j = index || 0, len1 = propArr.length; j < len1; j += 1) {
prop = propArr[j];
if (!resultingObj[prop]) {
resultingObj[prop] = {};
}
if (propArr[j + 1] === value_Str) {
resultingObj[prop] = propArr[j + 1];
j += 1;
} else {
createRec(propArr, resultingObj[prop], j + 1);
j = len1;
}
}
}
console.log(processInput([
['propA', 'value'],
['propB', 'propC', 'propD', 'value'],
['propB', 'propF', 'value']
]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With