【问题标题】:Attributes not showing up in json, restructure json objects属性未显示在 json 中,重组 json 对象
【发布时间】:2019-12-01 20:08:13
【问题描述】:

原始json数据:

{
  "UniversalOne": "",
  "CommonOne": "",
  "Implementations": [
    {
      "BirthDate": "",
      "UniqueTraits": "",
      "Male": {
        "Gender": "Male",
        "PlaceOfBirth": "",
        "Weight": "",
        "Height": "",
        "EyeColor": ""
      },
      "Female": {
        "Gender": "Female",
        "PlaceOfBirth": "",
        "Weight": "",
        "Height": "",
        "EyeColor": ""
      },
      "Country": [
        {
          "Orientation": "Male",
          "Name": "ABCD",
          "County": "East"
        },
        {
          "Orientation": "Male",
          "Name": "ABCD",
          "County": "West"
        },
        {
          "Orientation": "Female",
          "Name": "EFGH",
          "County": "East"
        },
        {
          "Orientation": "Female",
          "Name": "EFGH",
          "County": "West"
        },
        {
          "Orientation": "Female",
          "Name": "IJKL"
        }
      ],
      "State": [
        {
          "Address": "XYZ Street",
          "ZipCode": "US"
        }
      ],
      "Boy": [
        {
          "AgeGroup": "A",
          "Id": 1,
          "MaternalName": "",
          "PaternalName": ""
        },
        {
          "AgeGroup": "B",
          "Id": 2,
          "MaternalName": "",
          "PaternalName": ""
        },
        {
          "AgeGroup": "C",
          "Id": 3,
          "MaternalName": "",
          "PaternalName": ""
        }
      ]
    }
  ],
  "PersonalityTraits": [
    {
      "Type": "Positive"
    },
    {
      "Type": "Negative"
    }
  ],
  "UniversalTwo": "",
  "CommonTwo": "",
  "EatingHabits": {
    "Type": "Excessive"
  },
  "ReadingHabits": {
    "Type": "Fast"
  },
  "FitnessHabits": {},
  "UniversalThree": "",
  "CommonThree": ""
}

预期的 json 响应:

  {
  "UniversalOne": "",
  "CommonOne": "",
  "Implementations": [
    {
      "BirthDate": "",
      "UniqueTraits": "",
      "Male": {
        "Gender": "Male",
        "PlaceOfBirth": "",
        "Weight": "",
        "Height": "",
        "EyeColor": "",
        "Country": [
          {
            "Orientation": "Male",
            "Name": "ABCD"
          }
        ],
        "EastCounty": {
          "Orientation": "Male",
          "Name": "ABCD",
          "County": "East"
        },
        "State": [
          {
            "Address": "XYZ Street",
            "ZipCode": "US"
          }
        ]
      },
      "Female": {
        "Gender": "Female",
        "PlaceOfBirth": "",
        "Weight": "",
        "Height": "",
        "EyeColor": "",
        "Country": [
          {
            "Orientation": "Female",
            "Name": "EFGH"
          },
          {
            "Orientation": "Female",
            "Name": "IJKL"
          }
        ],
        "EastCounty": {
          "Orientation": "Female",
          "Name": "EFGH",
          "County": "East"
        },
        "State": [
          {
            "Address": "XYZ Street",
            "ZipCode": "US"
          }
        ]
      },
      "Girl": [
        {
          "AgeGroup": "A",
          "identification": [
            {
              "Number": 1,
              "MaternalName": "",
              "PaternalName": ""
            }
          ]
        },
        {
          "AgeGroup": "B",
          "identification": [
            {
              "Number": 1,
              "MaternalName": "",
              "PaternalName": ""
            }
          ]
        },
        {
          "AgeGroup": "C",
          "identification": [
            {
              "Number": 1,
              "MaternalName": "",
              "PaternalName": ""
            }
          ]
        }
      ]
    }
  ],
  "PersonalityTraits": [
    {
      "Type": "Positive"
    },
    {
      "Type": "Negative"
    }
  ],
  "UniversalTwo": "",
  "CommonTwo": "",
  "EatingHabits": {
    "Type": "Excessive"
  },
  "ReadingHabits": {
    "Type": "Fast"
  },
  "FitnessHabits": {},
  "UniversalThree": "",
  "CommonThree": ""
}

问题:

我有三个具体问题:

1) 如何保留“男性”和“女性”正下方以及“男性”之前的属性?在我运行我的程序后,这些属性不会显示在我的响应中。

我想保留像

这样的属性
"BirthDate":"", 
"UniqueTraits": "" AND 

"Gender": "Male", 
"PlaceOfBirth": "", 
"Weight": "", 
"Height": "", 
"EyeColor": "" 

与我的原始和预期的 json 数据完全相同。

2) 我如何在男性和女性的 Country[] 之后添加另一个 EastCounty{},基于“County”:East 和 Orientation?请参考原始和预期的 json 以供参考。

3) 我如何将原始 json 中的 Boy[] 重构为新结构,正如预期 json 响应中的 Girl[] 所示?注意 Boy[] 中的“Id”更改为 Girl 中的“Number”。因此,如果“AgeGroup”中的任何一个中有多个“标识”,那么每个记录的“Number”都会按顺序更改。

当前节目:

function modifyImplementations(Implementations) {
  var finalResult = [];

  for (var i = 0; i < Implementations.Implementations.length; i++) {
    var currentImplementation = Implementations.Implementations[i];
    var targetObj = {
      "Male": {
        "Gender": "Male",
        "Country": [],
        "State": currentImplementation.State
      },
      "Female": {
        "Gender": "Female",
        "Country": [],
        "State": currentImplementation.State
      }
    };

    for (var j = 0; j < currentImplementation.Country.length; j++) {
      var currentCountry = currentImplementation.Country[j];
      if (currentCountry.Orientation === 'Male') {
        targetObj.Male.Country.push(currentCountry);
      } else if (currentCountry.Orientation === 'Female') {
        targetObj.Female.Country.push(currentCountry);
      }
    }
    finalResult.push(targetObj);
  }
  return finalResult
}

var x = Object.assign({}, Implementations);
x.Implementations = modifyImplementations(Implementations);

console.log(JSON.stringify(x));

【问题讨论】:

  • 正如您所问的,如果要保留大量属性,那么在您创建 targetObj 而不是创建新对象的地方将 currentImplementation 克隆到一个新对象中并制作对其进行更改,例如添加国家/州/县,最后从克隆的 obj 中删除国家/州数组并将所有这些返回到 finalResult,这样您就只会在需要的字段上工作!
  • 感谢您的回复,我无法在控制台中看到克隆的对象。 for (var i = 0; i
  • 不是 var originalObject = Object.assign({}, currentApplication),改成: var originalObject = Object.assign({}, currentImplementation) 也可以直接赋值: let originalObject = currentImplementation;确保此时 :: var x = Object.assign({}, Implementations); x.Implementations = modifyImplementations(Implementations);控制台.log(JSON.stringify(x)); Node.Js 等待 x.Implementations = modifyImplementations(Implementations);在打印 console.log 之前完成,因为 Node.Js 是异步的,请确保检查!!
  • 我已经更新了到目前为止的内容,因为我无法在评论框中添加内容。如何验证克隆的对象是否被正确复制?
  • 好的建议,如果你使用vscode作为你的IDE,然后尝试使用quokka扩展,这对代码的运行时分析非常有帮助,你只需要打开quokka选项卡(cmd +shift+p) 将打开一个新的 js 文件,然后粘贴您的代码并确保没有错误,使用少量 console.logs 进行快速检查!

标签: javascript node.js json node-modules


【解决方案1】:

这应该是可以产生预期结果的工作功能,请进行一些重构,因为肯定有更好的方法可以在少数代码区域中实现,只需在这里快速完成您的所有需求以产生预期的 o/p 以及您的问题需求用有效的 JSON 更新:

function modifyImplementations(Implementations) {

    for (let i = 0; i < Implementations.Implementations.length; i++) {
        let currentImplementation = Implementations.Implementations[i];

        currentImplementation['Male']['Country'] = []
        currentImplementation['Female']['Country'] = []
        currentImplementation['Male']['EastCounty'] = []
        currentImplementation['Female']['EastCounty'] = []
        currentImplementation['Male']['State'] = currentImplementation['State'];
        currentImplementation['Female']['State'] = currentImplementation['State'];

        for (let j = 0; j < currentImplementation.Country.length; j++) {
            let currentCountry = currentImplementation.Country[j];
            let currentCountryObj = {}
            if (currentCountry.Orientation === 'Male') {
                if (currentCountry.County && currentCountry.County == "East") {
                    currentCountryObj['County'] = currentCountry.County
                    currentCountryObj['Name'] = currentCountry.Name
                    currentCountryObj['Orientation'] = currentCountry.Orientation
                    currentImplementation['Male']['EastCounty'].push(currentCountryObj)
                } else {
                    currentCountryObj['Name'] = currentCountry.Name
                    currentCountryObj['Orientation'] = currentCountry.Orientation
                    currentImplementation['Male']['Country'].push(currentCountryObj);
                }
            } else if (currentCountry.Orientation === 'Female') {
                if (currentCountry.County && currentCountry.County == "East") {
                    currentCountryObj['County'] = currentCountry.County
                    currentCountryObj['Name'] = currentCountry.Name
                    currentCountryObj['Orientation'] = currentCountry.Orientation
                    currentImplementation['Female']['EastCounty'].push(currentCountryObj)
                } else {
                    currentCountryObj['Name'] = currentCountry.Name
                    currentCountryObj['Orientation'] = currentCountry.Orientation
                    currentImplementation['Female']['Country'].push(currentCountryObj);
                }
            }
        }
        delete currentImplementation['Country']
        delete currentImplementation['State']

        let mapObj = [];
        for (items of currentImplementation.Boy) {
            let objs = currentImplementation.Boy.filter((obj) => {
                return items.AgeGroup === obj.AgeGroup
            })
            mapObj.push(objs)
            currentImplementation.Boy = currentImplementation.Boy.filter(e => e.AgeGroup !== items.AgeGroup);
        }

        let finalArray = mapObj.filter(e => e.length > 0)
        currentImplementation['Girl'] = []
        for (anArray of finalArray) {
            let finalObj = {}
            finalObj.identification = [];
            if (anArray.length && anArray.length > 1) {
                let number = 1
                for (oneObj of anArray) {
                    let objs = {};
                    objs['Number'] = number
                    objs['MaternalName'] = oneObj['MaternalName']
                    objs['PaternalName'] = oneObj['PaternalName']
                    number += 1
                    finalObj['AgeGroup'] = oneObj.AgeGroup
                    finalObj.identification.push(objs);
                }
            } else if (anArray.length == 1) {
                let objs = {};
                finalObj['AgeGroup'] = anArray[0].AgeGroup
                objs = {};
                objs['Number'] = 1
                objs['MaternalName'] = anArray[0]['MaternalName']
                objs['PaternalName'] = anArray[0]['PaternalName']
                finalObj.identification.push(objs);
            }
            currentImplementation['Girl'].push(finalObj)
            delete currentImplementation['Boy']
        }
    }
    return Implementations
}

【讨论】:

  • 感谢您的回复。上面的代码肯定可以工作。我唯一的问题是当属性很大时,在这种情况下,在 targetObj 中添加所有属性会太密集。相反,有没有一种方法可以在“Male”{} 之前和之后推送属性,或者可以在控制台日志中以不同的方式打印以获取属性而不在 targetObj 中添加每个属性?我肯定要考虑有大量属性时的边缘情况。
  • @Eva :根据最新的 cmets 更新了答案,您的问题中有许多子问题,需要一些时间为所有场景编码/重构您的代码,并继续您的编码并让我们知道确切的位置你被困住了。让我们总结一下,而不是现在考虑性能因素..
  • 感谢您为帮助我所做的努力,感谢您及时回答我的问题。通过更新的答案和一些重构以将 Personality Traits 中的部分附加到底部,我能够看到“Male”之前和之后的属性。但是,EastCounty{} 在我的响应中是空的,并在 originalObject[ '男']['EastCounty'].push(currentCountryObj)。是因为它在原始对象中的声明方式吗?
  • 我已经测试了该代码并且它应该可以工作,你能给我错误或给我代码 lemme 检查是否有我可以快速修复的问题..
  • 你是对的,它只需要数组才能使推送函数有效,即 originalObject['Male']['EastCounty'] = []。它没有抛出任何错误,我明白了'EastCounty' 内的数据。但是,json 响应在我的响应中是 EastCounty[],因为它在 originalObject 中被声明为数组。预期的 json 响应是 'EastCounty' {}(大括号),它不是一个数组。如果我们将 push 函数声明为 originalObject['Male']['EastCounty'] = {},有没有办法仍然可以使用它,这就是我所做的更改并得到错误“push is not a valid function”。希望我的解释有所帮助!
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2018-03-29
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 2021-03-12
相关资源
最近更新 更多