Combine or merge JSON on node.js without jQuery

后端 未结 18 2059
醉话见心
醉话见心 2020-12-07 17:17

I have multiple JSON like those

var object1 = {name: \"John\"};
var object2 = {location: \"San Jose\"};

They are not nesting o

18条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 17:45

    Here is simple solution, to merge JSON. I did the following.

    • Convert each of the JSON to strings using JSON.stringify(object).
    • Concatenate all the JSON strings using + operator.
    • Replace the pattern /}{/g with ","
    • Parse the result string back to JSON object

      var object1 = {name: "John"};
      var object2 = {location: "San Jose"};
      var merged_object = JSON.parse((JSON.stringify(object1) + JSON.stringify(object2)).replace(/}{/g,","))
      

    The resulting merged JSON will be

    {name: "John", location: "San Jose"}
    

提交回复
热议问题