简体   繁体   中英

add object to a complex json in javascript

Suppose there are two json objects as

1.

{
  "conditionTemp": null,
  "value": null,
  "variableValue": "flowParameters_3"
}

or

{
  "conditionTemp": {
    "functionID": "func_1",
    "parameters": [{}]
  },
  "value": null,
  "variableValue": null
}

and

2.

{
  "conditionTemp": {
    "functionID": "func_1",
    "parameters": [{
        "conditionTemp": null,
        "value": null,
        "variableValue": "flowParameters_3"
      },
      {
        "conditionTemp": {
          "functionID": "func_1",
          "parameters": [{}]
        },
        "value": null,
        "variableValue": "null"
      },
      {}
    ]
  },
  "value": null,
  "variableValue": null
}

ie the second object will have ("conditionTemp", "value", "variable"),

the first "conditionTemp" will have "functionID", "parameters"

inside "parameters" we can have any no. of objects. If inside parameters, the the object's "conditionTemp" value is not null , we have to check the parameter object inside of that. If the parameter object is empty, we have to insert the **first object there.**

So for the above jsons, on adding the first object onto the second, the resultant json will be

{
  "conditionTemp": {
    "functionID": "func_1",
    "parameters": [{
        "conditionTemp": null,
        "value": null,
        "variableValue": "flowParameters_3"
      },
      {
        "conditionTemp": {
          "functionID": "func_1",
          "parameters": [{
                 "conditionTemp": null,
                 "value": null,
                 "variableValue": "flowParameters_3"
           }]
        },
        "value": null,
        "variableValue": "null"
      },
      {}
    ]
  },
  "value": null,
  "variableValue": null
}

First level would be like this:

 var obj_a = { "conditionTemp": { "functionID": "func_1", "parameters": [{ "conditionTemp": null, "value": null, "variableValue": "flowParameters_3" }, { "conditionTemp": { "functionID": "func_1", "parameters": [{}] }, "value": null, "variableValue": "null" }, {} ] }, "value": null, "variableValue": null }; var obj_b = { "conditionTemp": null, "value": null, "variableValue": "flowParameters_3" }; var final_obj = Object.keys(obj_a).reduce(function(data, key) { if (obj_a[key] == null && obj_b[key] != null) data[key] = obj_b[key]; else data[key] = obj_a[key]; return data; }, {}); console.log(final_obj); 

Second and further levels would be tricky. Is the format always like that? In your example, values could be (string, null, array of objects)... are there other formats not mentioned or that you wouldn't know?

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