用其他json文件中的对象替换字符串

时间:2016-12-11 07:09:05

标签: javascript json node.js underscore.js lodash

我有3个json文件:

  1. sources.json
  2. destination_level1.json
  3. destination_level0.json(最终文件)
  4. 我想通过替换匹配的字符串来“合并”所有这些文件,例如

    destination_level0 - > destination_level1 - >来源

    单词:“检查destination_level0中的键,例如”Element1“,转到destination_level1并查找匹配的对象,并将destination_level0中的Element1替换为该对象。”从destination_level1到源也是如此。

    来源可能如下所示:

    {"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}}
    

    destination_level_1是这样的:

    {"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]}
    

    和destination_level_0是这样的:

    {"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]}
    

    最终结果应如下所示:

    {"FinalA": [[["A","B"],{"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]},...
    

    我尝试了一些lodash&强调,但卡住了。

    有什么想法吗?

2 个答案:

答案 0 :(得分:0)

仅使用纯JavaScript

var sources = {"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}};
    var destination_level_0 = {"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]};
    var destination_level_1 = {"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]};
    
    var final = {};
    for(var key in destination_level_0){
        var preFinal = [];
        var elems = destination_level_0[key];
        for(var i in elems){
            var elem = elems[i];
            var names = destination_level_1[elem];
            for(var j in names){
                var name = names[j];
                var finalItem = sources[name];
                preFinal.push(finalItem); 
            }
        }
        final[key] = preFinal;
    }
    
    console.log(final);
    console.log(JSON.stringify(final));

答案 1 :(得分:0)

映射level0 =>中的项目level1 =>在Array#map(或lodash的Array#.map)内使用_.map()的level2:

var level0 = {"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]};
var level1 = {"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]};
var level2 = {"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}}
;

var result = Object.keys(level0).reduce(function(r, key) {
  r[key] = level0[key].map(function(element) {
    return level1[element].map(function(item) {
      return level2[item];
    });
  }) 
  
  return r;
}, Object.create(null));

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