javascript
  • arrays
  • json
  • 2016-09-25 79 views -1 likes 
    -1

    我有這樣的JSON:的foreach元素的Javascript JSON

    { 
        "email.com": ["[email protected]|username\r"], 
        "email.de": ["[email protected]|username"] 
    } 
    

    我想要得到它printet這樣的:

    email.com
    email.de

    var data = '{"email.com":["[email protected]|username\r"],"email.de":["[email protected]|username"]}'; 
     
    var obj = JSON.parse(data); 
     
    for (i = 0; i < obj.length; i++) { 
     
        document.getElementById('types').innerHTML += '<br>' + obj[i]; // I want to get email.com , email.de 
     
    }
    <div id="types"> 
     
    </div>

    +0

    它是關於獲得只是一個對象的屬性名稱。用戶名不被考慮? – RomanPerekhrest

    +0

    不,我只是想得到email.com和email.de的陣列的名稱 –

    +0

    如果是這樣,沒有必要分析該字符串 – RomanPerekhrest

    回答

    0
    var data = [{"email.com":["[email protected]|username\r"],"email.de":["[email protected]|username"]}]; 
    var term = (Object.keys(data[0])[0]); 
    
    var obj = JSON.parse(data); 
    for (i = 0; i < obj.length; i++) { 
        document.getElementById('types').innerHTML += '<br>' + obj[i][term]; // I want to get email.com , email.de 
    } 
    

    這應該工作

    Printing object's keys and values

    +0

    未捕獲的ReferenceError:未定義的過濾器 –

    +0

    @shkumbinhasani請參閱編輯 –

    +0

    JSON中的意外標記o位置1 –

    0

    簡單的解決方案使用String.matchArray.join功能:

    var data = '{"email.com":["[email protected]|username\r"],"email.de":["[email protected]|username"]}', 
     
        emails = data.match(/\w+\.\w+(?=\":\[)/g).join("<br>"); 
     
        
     
    document.getElementById('types').innerHTML += '<br>' + emails; 
     
    // 'emails' variable contains "email.com<br>email.de"
    <div id="types"></div>

    2

    這工作得很好:

    var data = '{"email.com":["[email protected]|username\\r"],"email.de":["[email protected]|username"]}'; 
     
    var obj = JSON.parse(data); 
     
    var keys = Object.keys(obj); 
     
    for (i = 0; i < keys.length; i++) { 
     
        document.getElementById('types').innerHTML += '<br>' + keys[i]; // I want to get email.com , email.de 
     
    }
    <div id="types"></div>

    +0

    非常感謝:D –

    +0

    你現在知道我想要找那個鑰匙的孩子,你能幫我嗎 –

    +0

    var data ='{「email.com」:[「[email protected] | username \\ r 「],」 email.de 「:[」 [email protected]|username「]}」; var obj = JSON.parse(data); var keys = obj; 爲(在OBJ變種X){ \t如果(obj.hasOwnProperty(X)){ \t的document.getElementById( '類型')的innerHTML + = '
    ' + OBJ [X]。 } } – sidanmor

    0

    迅速:

    var obj = { 
        "email.com": ["[email protected]|username\r"], 
        "email.de": ["[email protected]|username"] 
    }; 
    for (var prop in obj) console.log(prop); 
    
    相關問題