简体   繁体   English

分隔键值对并将其放在另一个数组中

[英]Separate key value pair and putting it in another array

I have an JSON object like this: 我有一个像这样的JSON对象:

{
  "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? 我该如何实现?

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

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

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/ 您可以在下面的链接中检查https://jsfiddle.net/Siddharth_Pandey/4d2u640w/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将键值对中的一个值设置为数组中的另一个键? - Setting one value in Key value pair to another key in an array? 如何检查键值对(在数组中)是否存在于另一个数组中? - How to check if a key value pair (in an array) exists in another array? 学习 JS - 你如何从一个键/值对中检索一个值,当该对本身是另一个对的值,都在一个数组中? - Learning JS - How do you retrieve a value from a key/value pair, when that pair is itself a value of another pair, all within an array? 将键值对存储在数组中 - Storing key value pair in array javascript中具有键值对的数组中的键值对 - Key Value pair from an array with key Value pair in javascript 如何基于另一个键值将新的键值对添加到数组中的对象 - How to add new key value pair to an object in an array based on another key-value 如何在javascript中将数组键和值对中的值分配给另一个数组? - how to assign values in array key and value pair one array to another array in javascript? 将JSON数组推入数组的键值对 - push JSON array into key value pair of an array 将 [key, value] 的 'value' 配对成数组 - Make 'value' of [key, value] Pair into Array 在嵌套在另一个数组中的数组中返回具有特定key:value对的对象-Javascript - Return object with specific key:value pair in an array nested in another array - Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM