Himmel Himmel - 7 months ago 39
Javascript Question

Recursively add object properties

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,
(as a child of
) 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?


createRec recursively creates the object in a nested form.

function processInput(propsToAdd) {
  var resultingObj = {},

  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;

  ['propA', 'value'],
  ['propB', 'propC', 'propD', 'value'],
  ['propB', 'propF', 'value']