Replace value while iterating through nested json file in javascript

Viewed 5379

I've searched for a long time, but cannot find any solution for my problem... I got a random nested json object like this:

var obj = { a: 1, b: 2, c: { a: 1, b: 2, c: {a: 'hello', b: 'HowAreYou?'} } };
someValue = 'hello';
newValue = 'bye';

Now I'm going to search for 'someValue'. If 'obj' contains this value the alert will be triggered. Here's my example:

function wannaChangeValue(obj) {
    var itemKey;
    if (obj instanceof Object) {
        for (itemKey in obj) {
            if (obj.hasOwnProperty(itemKey)) {
                wannaChangeValue(obj[itemKey]);
            }
        }
    } else {
        alert(obj);
        if (obj == someValue) {
            alert('got it! now change...')
            //change someValue to newValue 
        }
    }
    return obj
}

wannaChangeValue(obj)

This works really fine, but how can I change 'someValue' to 'newValue' and return the whole json-file again? I've seen many examples how to handle this, but I need a solution for ANY kind of nested json object WITHOUT knowing the path for changing this value. Maybe this is a completely wrong approach... Thanks in advance!

6 Answers

Here is a solution using object-scan

// const objectScan = require('object-scan');

const obj = { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 'hello', b: 'HowAreYou?' } } };

const replace = (input, oldValue, newValue) => objectScan(['**'], {
  abort: true,
  rtn: 'bool',
  filterFn: ({ value, parent, property }) => {
    if (value === oldValue) {
      parent[property] = newValue;
      return true;
    }
    return false;
  }
})(input);

console.log(replace(obj, 'hello', 'bye')); // returns true iff replace happened
// => true
console.log(obj);
// => { a: 1, b: 2, c: { a: 1, b: 2, c: { a: 'bye', b: 'HowAreYou?' } } }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.7.1"></script>

Disclaimer: I'm the author of object-scan

Related