0

For example, I have data like this

data = {
    code:1,
    status: 200,
    data:[{
        name: {
            first: 'first',
            last: 'last',
        },
        age: 12,
        address: "address",
        ...
    },
    ...
    ,{
        ...
    }]
}

key = 'data[0].name.last';

I want to change the value data.data[0].name.last and I know last value's path(key) is data[0].name.last.

data[key] = 'last1' doesn't work because of array index. Is there any method to solve this problem?

mings
  • 31
  • 6
  • Try eval? Although that isn't the best way. – Chang Alex Jul 14 '22 at 04:25
  • Maybe `const value="last1"; eval(key+'"'+value.replace(/"/g,'\\"')+'"')` – Chang Alex Jul 14 '22 at 04:27
  • 1
    I'd just use Lodash ~ https://lodash.com/docs/4.17.15#set – Phil Jul 14 '22 at 04:28
  • if you dont want the whole lodash https://www.npmjs.com/package/lodash.set . here is the source https://github.com/lodash/lodash/blob/master/set.js . a solution here on SO https://stackoverflow.com/questions/54733539/javascript-implementation-of-lodash-set-method – cmgchess Jul 14 '22 at 04:31

0 Answers0