在JavaScript中将对象转换为对象内的数组

时间:2017-03-02 20:44:02

标签: javascript arrays json

我以处理系统无法接受的格式获取数据,而我正在尝试转换数据。下面是我获得的数据以及下面所需的JSON。我尝试了不同的方法,例如在数据中查找Object并检查它是否包含多个元素,然后将该对象转换为Array[],但我无法这样做。

如果您有任何意见,我将不胜感激。

if(typeof ob1=== "object" && Object.keys(ob1.length > 1) && typeof Object.keys(ob1) === "object" )
{
    console.log(ob1); // I get all the objects and not the parent object i need to change. 
}

现有数据:

ob1 : {id: 1, details: Object, profession: "Business"}

JSON:

{
  "id": "1",
  "details": {
    "0": {
      "name": "Peter",
      "address": "Arizona",
      "phone": 9900998899
    },
    "1": {
      "name": "Jam",
      "address": "Kentucky",
      "phone": 56034033343
    }
  },
  "profession": "Business"
}

必填数据

{id: 1, details: Array[2], profession: "Business"}

必需的JSON:

{
  "id": "1",
  "details": [
    {
      "name": "Peter",
      "address": "Arizona",
      "phone": 9900998899
    },
    {
      "name": "Jam",
      "address": "Kentucky",
      "phone": 56034033343
    }
  ],
  "profession": "Business"
}

1 个答案:

答案 0 :(得分:2)

您必须浏览详细信息对象并将其转换为数组:

height