繁体   English   中英

在javascript中复制部分json键值

[英]Copy part of json key-values in javascript

给定这样的 json

  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };

如何获得这样的新 json,它只会将相同的密钥复制到第一个。

json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};

我试过_.assignObject.assign或 _.assign

 Object.assign(json1,json2)
 _.assign(json1,json2)

但它会将json2的所有对象复制到json1。

您可以使用Object.keysjson1获取所有键,然后检查该键是否存在于json2 ,如果存在则从 json2 中获取与该键对应的值

 var json1 = { "key1": { "index": "1", "value": null }, "key2": { "index": "2", "value": null }, "key3": { "index": "3", "value": null } } var json2 = { "key3": { "index": "3", "value": "value3" }, "key4": { "index": "4", "value": 'value4' } }; Object.keys(json1).forEach((item) => { if (json2.hasOwnProperty(item)) { json1[item].value = json2[item].value } }) console.log(json1)

 const json1 = { "key1": { "index": "1", "value": null }, "key2": { "index": "2", "value": null }, "key3": { "index": "3", "value": null } }; const json2 = { "key3": { "index": "3", "value": "value3" }, "key4": { "index": "4", "value": 'value4' } }; const result = {}; for(const key in json1) { result[key] = json2[key] ? json2[key] : json1[key]; }; console.log(result);
你可以使用for in

现场演示: https : //runkit.com/embed/0z916nnwl2w5

var output = Object.assign(json1,json2);
delete output.key4;  //Here is the key~~~
console.log(output);

在此处输入图片说明

暂无
暂无

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

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