1

I've got this JSON data object (example):

let obj = [
  {
    test0: [ 
      {testA: 'ContentA' },
      {testB: 'ContenB'}
    ] 
  }
];

I'd like to replace the value of key 'testB' dynamically. I.e. I need to be able to address any item in the object and replace ist.

Here's what I am doing so far:

Therefore I programmatically generate a mixed key/index path to address the target object and it looks like this (in array form):

let path = [0,'\'test0\'',1,'\'testB\''];

In order to put this in an executable form which does the actual replacement, I convert path to JavaScript code and run it with eval. Like this:

let newText = 'ContentB';
eval(`obj[${path.join('][')}]=\'${newText}\'`);

Eval executes this code literal:

obj[0]['test0'][1]['testB'] = 'ContentB'

This works, but if possible, I'd like to know if there's an alternative way which works without using "eval".

2
  • NB/ this has nothing to do with JSON. Please check out the usage description of the json tag. Commented Dec 13, 2018 at 13:32
  • You are absolutely right. I apologize. I have read the description and I admit it's not a JSON problem but a javascript Object problem. I will update the title accordingly. Commented Dec 13, 2018 at 14:06

1 Answer 1

2

You could use a recursive function and pass it the property path as an array of properties, like this:

function setDeepValue(obj, [prop, ...path], value) {
    if (!path.length) {
        obj[prop] = value; 
    } else {
        if (!(prop in obj)) obj[prop] = {};
        setDeepValue(obj[prop], path, value);
    }
}

// Example:
const arr = [{
    test0: [ 
        { testA: 'ContentA' },
        { testB: 'ContenB' }
    ]
}];
  
setDeepValue(arr, [0, "test0", 1, "testB"], "ContentB");

console.log(arr);

If you are OK with using a library, you could use Lodash, which has _.set and the more flexible _.setWith to do this.

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

2 Comments

I don't know, if I have misread your answer, but I am missing the part, where the new value is being set.
Updated to set a value.

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.