2

I have an object with a large nesting. I can change its content like this:

children.props.children.props.children = 'test'

I can do this:

children['props']['children']['props'].children = 'test'

I want to do this by having the path in a variable

let path = ['props','children','props']

I tried like this:

let path = ['props','children','props']
children[path].children = 'test'

let path = [['props'],['children'],['props']]
children[path].children = 'test'

But it doesn't work. Please tell me how can I use the "path" variable

2

3 Answers 3

2

You can try to "expand" the object by using an iterative approach:

const children = {
  props: {
    children: {
      props: {
        children: 'change me'
      }
    }
  }
};

const expandObject = (component, path) => {
  let ref = component;
  for (let i = 0; i < path.length; i++) {
    ref = ref[path[i]];
  }
  return ref;
};

let path = ['props', 'children', 'props'];

expandObject(children, path).children = 'test';

console.log(children);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Here is a recursive version that uses a depth:

const children = {
  props: {
    children: {
      props: {
        children: {
          props: {
            children: 'change me'
          }
        }
      }
    }
  }
};

const deepAccess = (component, depth) =>
  (depth === 0)
    ? component
    : deepAccess(component.props.children, depth - 1);

const ref = deepAccess(children, 2);

ref.props.children = 'test';

console.log(children);
.as-console-wrapper { top: 0; max-height: 100% !important; }

As others have shown, you can reduce the path:

const children = {
  props: {
    children: {
      props: {
        children: 'change me'
      }
    }
  }
};

const expandObject = (component, path) =>
  path.reduce((acc, path) => acc[path], component);

let path = ['props', 'children', 'props'];

expandObject(children, path).children = 'test';

console.log(children);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Sign up to request clarification or add additional context in comments.

Comments

1

This should work for you.

let path = ['props','children','props'];

const obj = { props: { children: { props: { children: null } } } };

let context = obj;

for (const name of path) {
  context = context[name];
}

context.children = "test";

console.log(obj)

Comments

0

This approach will create objects along the path if they don't already exist:

const obj = {a: { b: 'existing' }};

['a','c','d'].reduce((x,y)=>x[y]??={},obj).children = 'test'

console.log(obj)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.