将嵌套对象转换为对象数组

时间:2019-11-24 05:36:22

标签: javascript arrays typescript object

我想将下面的对象转换为特定格式,请参见。

我的对象看起来像

{
  "RecruiterInfo": {
    "Person": {
      "FirstName": "vals ererererre123",
      "LastName": "ravl2422",
      "CreatedOn": "1900-01-01T00:00:00",
      "Worktelephone": "",
      "PhoneNo": "9586391750",
      "Email": "vil@mailinator.comm",
      "UserId": {
        "Password": "Vm0wd2QyUXlWa1pOVldScFVtMVNjRlZ0TVZOWFJsbDNXa2M1VjJKSGVEQmFWVll3VjBaS2RHVkljRmRXTTJoeVZtMHhTMUl5VGtsaVJtUlhUVEZLVFZac1ZtRldNVnBXVFZWV2FHVnFRVGs9",
        "Status": 1,
        "ID": 1
      },
      "ID": 31
    },
    "CompanyName": "Teenr1242424",
    "Designation": "PM125554242",
    "BusinessType": 1179,
    "OrganizationSize": 1119,
    "IsVIP": 1
  }
}

我想将上述对象转换为

[
  {
    AppFieldID: "CompanyName",
    Value: "Teenr1242424"
  },
  {
    AppFieldID: "Designation",
    Value: "PM125554242"
  },
  {
    AppFieldID: "BusinessType",
    Value: 1179
  },
  {
    AppFieldID: "OrganizationSize",
    Value: 1179
  },
  {
    AppFieldID: "IsVIP",
    Value: 1
  },
  {
    AppFieldID: "Person",
    Value: [
      {
        AppFieldID: "FirstName",
        Value: "vals ererererre123"
      },
      {
        AppFieldID: "ID",
        Value: 1
      },
      {
        AppFieldID: "CreatedOn",
        Value: "1900-01-01T00:00:00"
      },
      {
        AppFieldID: "Email",
        Value: "vil@mailinator.comm"
      },
      {
        AppFieldID: "LastName",
        Value: "ravl2422"
      },
      {
        AppFieldID: "WorkTelephone",
        Value: ""
      },
      {
        AppFieldID: "PhoneNo",
        Value: "9586391750"
      },
      {
        AppFieldID: "UserId",
        Value: [
          {
            AppFieldID: "ID",
            Value: 1
          },
          {
            AppFieldID: "Password",
            Value: "Vm0wd2QyUXlWa1pOVldScFVtMVNjRlZ0TVZOWFJsbDNXa2M1VjJKSGVEQmFWVll3VjBaS2RHVkljRmRXTTJoeVZtMHhTMUl5VGtsaVJtUlhUVEZLVFZac1ZtRldNVnBXVFZWV2FHVnFRVGs9"
          },
          {
            AppFieldID: "Status",
            Value: 1
          }
        ]
      }
    ]
  }
]

它应该是动态代码,因为在功能中会有多个嵌套对象

任何人都可以帮助将该对象转换为上面的数组

我尝试通过使用一些嵌套循环并使用递归函数来对其进行转换,但是我无法进行转换。

谢谢 kj

1 个答案:

答案 0 :(得分:-1)

我希望这会有所帮助,让我知道是否有问题, 如果您想了解更多,请对recursion进行研究:

function convertObject(input) {
  const newObj =  Object.keys(input).map(key => {
    let Value = "";
    if(typeof input[key]=== 'object') {
      Value = convertObject(input[key])
    } else {
      Value = input[key];
    }
    return { AppFieldID: key, Value }
  });
  return newObj;
}
convertObject(yourObject.RecruiterInfo));