2017-03-02 121 views
0

我以不接受處理系統的格式獲取數據,並試圖轉換數據。以下是我獲得的數據和下面所需的JSON。我嘗試了不同的方法,例如在數據中查找Object,並檢查它是否有多個元素,然後將該對象轉換爲Array[],但我無法這樣做。將對象轉換爲JavaScript中的對象中的數組

如果您有任何意見,我將不勝感激。

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" 
} 
+2

JSON是一個字符串/文本格式。所以沒有像「JSON對象」或「JSON數組」那樣的東西。 –

回答

2

你必須要經過詳細信息對象,並將其轉換成一個數組:

var x = { 
    details: { 

    0: {a: 1}, 
    1: {a: 2} 
    } 
} 

var detailsArr = []; 

for(key in x.details) { 
    detailsArr.push(x.details[key]); 
} 

x.details = detailsArr; 

//x.details = [{a: 1}, {a: 2}] 
相關問題