简体   繁体   English

在javascript中遍历嵌套的json文件时替换值

[英]Replace value while iterating through nested json file in javascript

I've searched for a long time, but cannot find any solution for my problem... I got a random nested json object like this:我已经搜索了很长时间,但找不到任何解决我的问题的方法......我得到了一个随机嵌套的 json 对象,如下所示:

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'.现在我要搜索“someValue”。 If 'obj' contains this value the alert will be triggered.如果 'obj' 包含此值,将触发警报。 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?这真的很好用,但是我怎样才能将 'someValue' 更改为 'newValue' 并再次返回整个 json 文件? 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.我已经看到了很多如何处理这个问题的例子,但我需要一个解决任何类型的嵌套 json 对象的解决方案,而无需知道更改此值的路径。 Maybe this is a completely wrong approach... Thanks in advance!也许这是一个完全错误的方法......提前致谢!

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.您可以使用for...in循环创建函数,如果当前值匹配 oldValue 则更改该值。

 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.您可以定义一个函数,该value通过您的对象递归搜索该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/object-scan@13.7.1"></script>

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM