最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Replace value while iterating through nested json file in javascript - Stack Overflow

programmeradmin1浏览0评论

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 pletely wrong approach... Thanks in advance!

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 pletely wrong approach... Thanks in advance!

Share Improve this question asked Aug 3, 2017 at 9:46 EndivieEndivie 1011 gold badge2 silver badges8 bronze badges 1
  • Possible duplicate of Find and update in nested json object. Another link that might help: stackoverflow./questions/15523514/… – Rajesh Commented Aug 3, 2017 at 9:58
Add a ment  | 

6 Answers 6

Reset to default 4

You could use a recursice approach for any found object, call the function again.

function update(object, search, replace) {
    Object.keys(object).forEach(function (k) {
        if (object[k] && typeof object[k] === 'object') {
            return update(object[k], search, replace)
        }
        if (object[k] === search) {
            object[k] = replace;
        }
    });
    
}

var object = { a: 1, b: 2, c: { a: 1, b: 2, c: {a: 'hello', b: 'HowAreYou?'} } };
    
update(object, 'hello', 'bye');

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

You can create function using for...in loop and if current value match oldValue change that value.

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

function changeVal(data, oldV, newV) {
  for(var i in data) {
    if(typeof data[i] == 'object') changeVal(data[i], oldV, newV);
    if(data[i] == oldV) data[i] = newV
  }
  return data
}

console.log(changeVal(obj, someValue, newValue))

You can define a function which search recursively the value through your object and then replace this value.

function replaceObj (obj, valueForSearch,valueForReplace) {
    for (var key in obj) {
        var value = obj[key];
        if (typeof value === 'object') {
            replaceObj(value, valueForSearch,valueForReplace);
        }
        if (value === valueForSearch) {
            obj[key]=valueForReplace;
        }
    }
}
let obj = { a: 1, b: 2, c: { a: 1, b: 2, c: {a: 'hello', b: 'HowAreYou?'} } };
let someValue = 'hello';
let newValue = 'bye';
replaceObj(obj,someValue,newValue);
console.log(obj);

This is a quick solution:

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

wannaChangeValue(obj)

Obviously this will mutate the value on the object itself, so if you want an entirely new object you will have to do something different.

You could use recursive call for your object.

Demo

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

function wannaChangeValue(obj) {
  var itemKey;
  if (obj instanceof Object) {
    for (itemKey in obj) {
      if (obj.hasOwnProperty(itemKey)) {
        if (!(obj[itemKey] instanceof Object) && obj[itemKey] == someValue) {
          //alert(someValue + ' got it! now change...')
          //change someValue to newValue
          obj[itemKey] = newValue;
          break;
        } else {
          wannaChangeValue(obj[itemKey]);
        }
      }
    }
  }
}
wannaChangeValue(object);
console.log(object)
.as-console-wrapper {max-height: 100% !important;top: 0;}

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/[email protected]"></script>

Disclaimer: I'm the author of object-scan

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>