0

I have an JSON object like this:

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

I want an array like this:

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

How do i achieve it?

2
  • What specifically are you having problems with? Commented Feb 10, 2017 at 5:24
  • you could parse the string "name" to the key "name" and everything would be easier Commented Feb 10, 2017 at 5:28

3 Answers 3

1

How about something like this:

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

Sign up to request clarification or add additional context in comments.

Comments

1

You need to reorganize your object and that's it.

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

1 Comment

i did it the same way but i used if else instead of the ternary operator.
0

If you want the class type of the "type" property of your object you can try below code

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

You can check below link https://jsfiddle.net/Siddharth_Pandey/4d2u640w/

3 Comments

I would presume he wants the value of the type property if it's a string, or "Array" if it's an array. If I change that first type to "number" your code returns "String" for the first type.
His question was not that clear that's why I mentioned in my answer "If you want the class type of the "type" property of your object you can try below code"
I think it's pretty clear that "type": "number" shouldn't give the result "string".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.