【问题标题】:Fill a JSON from another using javascript使用 javascript 从另一个填充 JSON
【发布时间】:2018-10-30 07:17:15
【问题描述】:

给定一个空的 JSON 1:

JSON1 = {
  "person": { "firstName": "" },
  "products": { "packName": "", "packSize": "" }
}

JSON 2 的字段比 JSON 1 多:

JSON2 = {
  "person": { "firstName": "Ahmed", "job": "Doctor" },
  "products": { "packName": "antibiotic", "packSize": "large" }
}

我想用 JSON 2 中的对应值填充 JSON 1

{
  "person": { "firstName": "Ahmed" },
  "products": { "packName": "antibiotic", "packSize": "large" }
}

我尝试了几种方法,但没有到达那里

var newObj = {};
var parsedJson1 = JSON.parse(tw.local.JSON1);
var parsedJson2 = JSON.parse(tw.local.JSON2);
var i;

for (i in parsedJson1) {
    var key=i;
    var subkey=i;
    for (j in parsedJson2) {
        var k=j;
        var s=j;
        if (key == k && subkey == s) {
            newObj[key][subkey] = parsedJson2[j];
        }
    }
}
tw.local.stringifiedJSON = JSON.stringify(newObj);

【问题讨论】:

  • 变量k、s、key和subkey的值是什么,你没有初始化它们if条件如何工作?
  • key = i and k= j

标签: javascript json foreach


【解决方案1】:

下面是一个例子:

请注意,这假设如下:

  1. 您知道第二个对象将拥有所有必需的键。
  2. 第一层的所有值都是对象
  3. 请注意,此解决方案仅适用于指定的结构,如果您需要处理任何变化,则需要使其更具防御性。

步骤:

  • 遍历有效键(JSON1 上的所有键)
  • 对于每个有效密钥,将其添加到newObj 并遍历有效的subKeys
  • 将值从JSON2 复制到newObj

注意:我稍微修改了你的代码,以便可以在这个网站上执行

const JSON1 = `{
  "person": { "firstName": "" },
  "products": { "packName": "", "packSize": "" }
}`;

const JSON2 = `{
  "person": { "firstName": "Ahmed", "job": "Doctor" },
  "products": { "packName": "antibiotic", "packSize": "large" }
}`;


const parsedJson1 = JSON.parse(JSON1);
const parsedJson2 = JSON.parse(JSON2);
const newObj = {};
const validKeys = Object.keys(parsedJson1);

for (let i of Object.keys(parsedJson1)) {
  if (newObj[i] === undefined) {
    newObj[i] = {};
  }
  for (let j of Object.keys(parsedJson1[i])) {
    newObj[i][j] = parsedJson2[i][j];
  }
}

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

【讨论】:

    【解决方案2】:

    您应该使用递归来遍历目标对象以获得稳健性。我对代码进行了格式化以提高可读性。

    function getNode(obj, path) {
        var ret = obj;
        try {
            // replace forEach with for-loop for browser compatibilities
            path.forEach(function (p) {
                ret = ret[p];
            });
        } catch (e) {
            return undefined;
        }
        return ret;
    }
    
    function fillJSONWithAnother(target, source, path) {
        if (!(target && source)) return target;
        // Assign path as an empty array for first call
        path = path || [];
    
        // Get target node and source node for comparing
        var targetValue = getNode(target, path);
        var sourceValue = getNode(source, path);
        // targetValue is not a leaf node (i.e. is Object), should traverse its children nodes
        if (targetValue && typeof targetValue === "object") {
            for (var key in targetValue) {
                fillJSONWithAnother(target, source, path.concat([key]));
            }
        }
        // targetValue is a leaf node (i.e. not Object) and source value exists, set corresponding value
        else if (sourceValue !== undefined) {
            var node = getNode(target, path.slice(0, path.length - 1));
            node[path[path.length - 1]] = sourceValue;
        }
        return target;
    }
    
    // Test case
    var obj1 = {
        "person": {
            "firstName": ""
        },
        "products": {
            "packName": "",
            "packSize": "l"
        }
    };
    var obj2 = {
        "person": {
            "firstName": "Ahmed",
            "job": "Doctor"
        },
        "products": {
            "packName": "antibiotic",
            "packSize": "large"
        }
    }
    fillJSONWithAnother(obj1, obj2);
    // {"person":{"firstName":"Ahmed"},"products":{"packName":"antibiotic","packSize":"large"}}
    

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      相关资源
      最近更新 更多