简体   繁体   中英

javascript: Sourcing defaults for one json object from another - handling arrays in different sort order

I am receiving a json as parameter and I also have a template base json. I need to check that all objects of the template json should are present in the tgt json and if not, need to initialize those variables with template json.

Following is my implementation.

var jsonBase = {  
  "Et":"Val_Retain",
  "A1": {    
      "A12": {
          "A12Array": [              
            {
                  "key1": "val1"
            },
            {
                 "key2": "val2"                   
            }
          ]
        }
      }
    }

var jsonTgt = {  
  "Et":"OldVal",
  "A1": {    
      "A12": {
          "A12Array": [              
            {
                  "key1": "val1Old_Retain"
            }            
          ]
        }
      }
    }

initKeys(jsonBase,jsonTgt)
function initKeys(obj,tgt) {   
    Object.keys(obj).forEach(function(element, key, _array) {        
        var cur;        

        if (typeof(tgt[element])=="undefined") {            
            tgt[element]=obj[element]
        }
        if (typeof(obj[element])=="object") {
                initKeys(obj[element],tgt[element])
        }
    })    
}

console.log(JSON.stringify(jsonTgt))

The output is:

{
    "Et": "OldVal",
    "A1": {
        "A12": {
            "A12Array": [{
                    "key1": "val1Old_Retain"
                }, {
                    "key2": "val2"
                }
            ]
        }
    }
}

There are two questions:

  • Is this correct approach or there could be a more efficient or a simpler one with available js/nodejs libs?
  • More Importantly - What do I do in case if the array sort order doesn't match with template as below.

Changed sort order

var json2 = {  
  "Et":"OldVal",
  "A1": {    
      "A12": {
          "A12Array": [              
            {
                  "key2": "val1Old_Retain"
            }            
          ]
        }
      }
    }

The above produces the following output:

{
    "Et": "OldVal",
    "A1": {
        "A12": {
            "A12Array": [{
                    "key2": "val1Old_Retain",
                    "key1": "val1"
                }, {
                    "key2": "val2"
                }
            ]
        }
    }
}

as against the desired:

{
    "Et": "OldVal",
    "A1": {
        "A12": {
            "A12Array": [{                  
                    "key1": "val1"
                }, {
                    "key2": "val1Old_Retain"
                }
            ]
        }
    }
}

Here is the first sample code I have been able to make and it works, however, I think that the way you implemented your code is wrong since I am pretty sure you could have done something much simpler if you had in mind functional programming methods ie those native methods from mdn , and those ones from lodash library don't forget to mark as answered if I did, otherwise please comment so I get more information about your exact situation

var _ = require('lodash')
let jsonInput = {
    "Et": "Val_Retain",
    "A1": {
        "A12": {
            "A12Array": [{
                "key1": "val1"
            }, {
                "key2": "val2"
            }]
        }
    }
}

let jsonInput2 = {
    "Et": "OldVal",
    "A1": {
        "A12": {
            "A12Array": [{
                "key1": "val1Old_Retain"
            }]
        }
    }
}

for (let key1 in jsonInput) {
    if (key1 === 'Et') {
        jsonInput[key1] = "OldVal"
    } else {
        for (let key2 in jsonInput[key1]) {
            for (let key3 in jsonInput[key1][key2]) {
                console.log(jsonInput[key1][key2][key3])
                let listOfKeys = getKeys(jsonInput[key1][key2][key3])
                console.log(listOfKeys)
                console.log(jsonInput2[key1][key2])
                console.log(key3)
                let listOfKeys2 = getKeys(jsonInput2[key1][key2][key3])
                console.log(listOfKeys2)
                let uniqkeys = _.uniq(listOfKeys.concat(listOfKeys2))
                let sortedUniqkeys = _.sortBy(uniqkeys)
                let result = []
                console.log('sortedUniqkeys', sortedUniqkeys)
                sortedUniqkeys.forEach((key4, i) => {
                    let doc = {}
                    if (listOfKeys2.indexOf(key4) != -1) {
                        jsonInput2[key1][key2][key3].forEach((e, i) => {
                            if (e[key4]) {
                                doc[key4] = e[key4]
                            }
                        })
                    } else {
                        jsonInput[key1][key2][key3].forEach((e, i) => {
                            if (e[key4]) {
                                doc[key4] = e[key4]
                            }
                        })
                    }
                    result.push(doc)
                    console.log(key4, jsonInput[key1][key2][key3][key4])
                    console.log(result)
                })
                jsonInput[key1][key2][key3] = result
            }
        }
    }
}

function getKeys(arr) {
    console.log(arr)
    return arr.reduce(function(accumulator, value, index, array) {
        for (let key3 in value) {
            accumulator.push(key3)
        }
        return accumulator
    }, []);
}

console.log(JSON.stringify(jsonInput))

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