单独的键值对并将其放入另一个数组中

时间:2017-02-10 05:22:44

标签: javascript

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

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

我想要一个这样的数组:

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

我如何实现它?

3 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

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

答案 1 :(得分:1)

你需要重组你的对象,就是这样。

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

var newJSON=[];

for(k in obj){
    var v=obj[k];
    newJSON.push({
        fieldName:k,
        fieldType:Array.isArray(v.type)?"Array":v.type;
    });
}

console.log(newJSON);

答案 2 :(得分:0)

如果您想要对象的“type”属性的类类型,可以尝试下面的代码

 var inputData = {
  "name": {
    "type": "string"
  },
  "addresses": {
    "type": [
      "Address"
    ]
  }
};
var finalArray = [];
for (key in inputData) {
  finalArray.push({ fieldName: key, fieldType: Object.prototype.toString.call(inputData[key].type).slice(8, -1) });
}
console.log(finalArray);

您可以查看以下链接https://jsfiddle.net/Siddharth_Pandey/4d2u640w/