简体   繁体   中英

Copy part of json key-values in javascript

Given a json like this

  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'
              }
        };

how to get a new json like this, it will only copy the same key to the first one.

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

I've tried on Object.assign or _.assign of lodash

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

but it will copy all the objects of json2 to json1.

You can use Object.keys to get all the keys from json1 then check if the key exist in json2 ,if it exists then get the value corresponding to that key from 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);
You can use a for in for it.

Live Demo: https://runkit.com/embed/0z916nnwl2w5

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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