简体   繁体   English

javascript:从另一个来源采购一个json对象的默认值-以不同的排序顺序处理数组

[英]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. 我收到一个json作为参数,我也有一个基于模板的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. 我需要检查模板json的所有对象都应该存在于tgt json中,如果没有,则需要使用模板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? 这是正确的方法,还是有可用的js / nodejs库,可能是更有效或更简单的方法?
  • 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 这是我能够制作的第一个示例代码,并且可以运行,但是,我认为实现代码的方式是错误的,因为我敢肯定,如果您牢记函数式编程方法,那么您可以做得简单得多。 那些来自mdn的本地方法 ,以及来自lodash库的 那些本地方法 ,如果我这样做,请不要忘记将其标记为已回答,否则请发表评论,以便我获得有关您的具体情况的更多信息。

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))

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

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