2017-01-24 36 views
-2

我有以下的JSON對象轉換JSON對象JSON數組附加要素

{ 
    "https://www.google.com": "200", 
    "https://www.facebook.com": "200", 
    "https://www.yahoo.com": "401", 
    "https://www.friendster.com": "404" 
} 

是否有可能將其轉換爲一個JSON數組在JavaScript中附加元素(URL &狀態)?

[ 
    { 
    "url": "https://www.google.com", 
    "status": "200" 
    }, 
    { 
    "url": "https://www.facebook.com", 
    "status": "200" 
    }, 
    { 
    "url": "https://www.yahoo.com", 
    "status": "401" 
    }, 
    { 
    "url": "https://www.friendster.com", 
    "status": "404" 
    } 
] 

謝謝你的提示。

+2

**是**。這是可能的。只有你需要編寫一些代碼。添加一些你已經嘗試過的代碼。 – Manwal

+0

迭代現有對象並創建一個新數組。 –

回答

2

使用JSON.parse解析字符串,得到所有的鍵作爲數組和構造對象與URL和狀態屬性的陣列

var json = '{\ 
    "https://www.google.com": "200",\ 
    "https://www.facebook.com": "200",\ 
    "https://www.yahoo.com": "401",\ 
    "https://www.friendster.com": "404"\ 
}'; 
var obj = JSON.parse(json); 

var objWithUrlAndStatus = Object.keys(obj).map(function (key) { 
    return { 
     url: key, 
     status: obj[key] 
    } 
}); 

console.log(objWithUrlAndStatus); 
+0

謝謝。我是初學者。可以提供有關Object.keys(obj).map(function(key)的更多信息? – snorlax

+0

@snorlax Object.keys返回一個數組,其內容包含所有(自己的,未繼承的)可枚舉屬性(在您的情況下,所有URL, '[「https://www.google.com」,「https://www.facebook.com」,...]')。'map'是一個數組對象的方法,可以讓你創建一個新的數組因此,我們將源數組中的每個URL映射到一個包含'url'屬性的對象,該屬性的值是URL和'status'屬性,我們從解析的JSON中讀取值URL關鍵字 – Rafael

+0

@snorlax關於[Object.keys]的文檔(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)和[Array.prototype.map] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) – Rafael

1

您可以使用jQuery。每$

這樣

var data = { 
 
    "https://www.google.com": "200", 
 
    "https://www.facebook.com": "200", 
 
    "https://www.yahoo.com": "401", 
 
    "https://www.friendster.com": "404" 
 
}; 
 
var finalData=[]; 
 
$.each(data,function(index,val){ 
 
    finalData.push({url:index,status:val}); 
 
}); 
 

 
console.log(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>