JavaScript:通过字符串数据路径更改JSON中的数据

时间:2018-02-26 06:23:32

标签: javascript json

让我们说,我有以下JSON,它可以很容易地来回转换为JavaScript对象:

{
    "foo": {
        "bar": "Common substitute word",
        "baz": "Another common substitute word",
        "questionWords": {
            "wat": "Inadequate question word",
            "wut": "Even more inadequate question word"
        }
    }
}

我在另一个JSON文件中收到关于此JSON的修改,如下所示:

{
    "foo.questionWords.wut": "A question word to avoid"
}

所以修改的路径是以字符串 的形式给出。我必须通过新数据修改第一个JSON。

新数据路径可能不存在:

{
    "foo.callingWords.dude": "Commonly used synonym for pal"
}

新数据路径可能具有不确定深度

{
    "who.knows.how.deep.we.will.go": "Look, a penny!"
}

没有JS库处理这个问题的最佳方法是什么,仅仅是简单的Vanilia JS?

(您可以使用最新的JavaScript功能。)

感谢您的帮助!

4 个答案:

答案 0 :(得分:0)

vanillaJS中的一个选项,你可以使用eval(但是害怕,非常害怕!) 像这样:

var t = {
    "foo": {
        "bar": "Common substitute word",
        "baz": "Another common substitute word",
        "questionWords": {
            "wat": "Inadequate question word",
            "wut": "Even more inadequate question word"
        }
    }
};

eval("t.foo.bar = 13")

enter image description here

答案 1 :(得分:0)

基本上与每个人的答案相同,只是避免使用eval(),如果这可能是个问题。



const changeCloud = () => {
  return ('hello');
}

const mapStateToProps = () => ({
  cloud: changeCloud(),
  menuItems: menuItems,
})

const mapDispatchToProps = (dispatch) => ({
  setCloud: (value) => {
    dispatch(setCloud(value));
  },
})

const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(HeaderPresentational);




答案 2 :(得分:0)

我的解决方案使用递归函数。



const modifyObject = (object, jsonPath, value) => {
  const keys = jsonPath.split(".");
  const key = keys.splice(0, 1);
  if (keys.length > 0) {
    modifyObject(object[key], keys.join('.'), value)
  } else {
    object[key] = value;
  }
}

const obj = {
  foo: {
    bar: 11,
    baz: 12,
    bac: {
      leng: 1,
      str: 'hello world'
    }
  }
};

modifyObject(obj, 'foo.bac.leng', 'modified');

console.log(JSON.stringify(obj));




答案 3 :(得分:0)

我只是突变来源的命令式风格:

updateAll = function(source, target) {
    Object.keys(target)
        .forEach((k) => update(source, k, target[k]));
}

update = function(source, targetKey, targetValue) {
var keys = targetKey.split('.');

    // Iterate as long as there are keys to shift out and as long as source is
    // defined for that key.
     while((key = keys.shift()) && source[key]) {

        // If we're at a leaf, assign new value. Otherwise, iterate further into
        // the object.
        if (keys.length === 0 && typeof source[key] !== 'object') {
            source[key] = targetValue;
        } else {
            source = source[key];
        }
    }
}