我有一个像这样的JSON对象:

{
  "name": {
    "type": "string"
  },
  "addresses": {
    "type": [
      "Address"
    ]
  }
}


我想要这样的数组:

[{
  "fieldName": "name",
  "fieldType": "string"
 },
 {
  "fieldName": "address",
  "fieldType": "Array"
 }]


我该如何实现?

最佳答案

这样的事情怎么样:



function convertFieldType(fieldType) {
  if (Array.isArray(fieldType)) {
    return "Array";
  }

  return fieldType;
}

function getFieldTypes(definition) {
  return Object.keys(definition).map(function(fieldName) {
    return {
      fieldName: fieldName,
      fieldType: convertFieldType(definition[fieldName].type)
    };
  });
}

var def = {
  "name": {
    "type": "string"
  },
  "addresses": {
    "type": [
      "Address"
    ]
  }
};

console.log(getFieldTypes(def));

关于javascript - 分隔键值对并将其放在另一个数组中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42152053/

10-10 10:50