-2

I have a path of the child object in a parent object. This path is combination of arrays and objects const path = ['one', 'two', '0', 'three', '2']; and parent object will be

const root = {
    'one' : {
        'two': [
            {
                'three': [
                    {}, 
                    {}, 
                    {
                    'deleterObject': 'yes'
                    }
               ]
            },
          [], []
        ],
        c: [], 
        d: []
    }
}

after doing this execution, final output should look like,

const root = {
    'one' : {
        'two': [
            {
                'three': [
                    {}, 
                    {}
               ]
            },
          [], []
        ],
        c: [], 
        d: []
    }
}

function that I wrote is,

const deleteObject = (root, path) => {
    let concated = '';
    for(let child in pathArray) {
        if(child > 0) concated = concated.concat(`[${pathArray[child]}]`)
        else concated = `[${pathArray[child]}]`
    }
    delete concated;
    return root
}

But its returning an error, Please suggest some function to do this.

2
  • 1
    What's the error? Commented Nov 16, 2020 at 0:12
  • Its keep on going to the loop, getting stuck Commented Nov 16, 2020 at 0:31

1 Answer 1

3

You can grab the last property from your path array (ie: 2), and then use .reduce() to walk down each property of path in root. Eventually, you'll reach the object which you want to delete from. You can check if this is an array using Array.isArray(), and then .splice() to remove the item. If it is not an array, you can use delete to delete the property from your object:

const path = ['one', 'two', '0', 'three', '2'];
const root = { 'one': { 'two': [{ 'three': [{}, {}, { 'deleterObject': 'yes' } ] }, [], [] ], c: [], d: [] } }

const deleteObject = (root, [...path]) => {
  const propToDel = path.pop();
  const toDeleteFrom = path.reduce((obj, p) => obj[p], root);
  if(Array.isArray(toDeleteFrom))
    toDeleteFrom.splice(propToDel, 1);
  else
    delete toDeleteFrom[propToDel];
}

deleteObject(root, path);
console.log(root);
.as-console-wrapper { max-height: 100% !important;} /* ignore */

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

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.