2017-05-06 38 views
0

我試圖獲取HTML列表的文本值,然後將它們推送到JSON對象中的單個鍵值。我希望JSON內容看起來像{"players": ["James","Emma","Vincent"]}。我目前的嘗試如下。如何將HTML列表值作爲javascript中的數組推送到單個JSON密鑰

// create array with empty player key 
 
var infoArray = [{ 
 
    "players": "" 
 
}]; 
 
// set the player key to a var 
 
var mykey = 'players'; 
 

 
// for each player 
 
$(".player").each(function() { 
 
    infoArray[mykey].push({ 
 
     // add the player's name to the key 
 
     $(this).text(); 
 
    }); 
 
}); 
 

 
//show the resulting json 
 
$("#list").html(JSON.stringify(infoArray));
pre { 
 
    word-wrap:break-word; 
 
    padding:10px; 
 
    margin:10px; 
 
    background:#eee; 
 
    line-height: 1.7 
 
}
<ul> 
 
    <li class="player">James</li> 
 
    <li class="player">Emma</li> 
 
    <li class="player">Vincent</li> 
 
</ul> 
 
<h3>JSON result</h3> 
 
<pre id="list"></pre>

回答

1

幾件事情:

1)無需{push()功能}

infoArray[mykey].push({ // <-- here 
    $(this).text(); 
}); 

2)不要初始化關鍵player爲空字符串""的價值,而不是使用空數組[]。請注意,infoArray是一個JSON數組而不是JSON對象。


// create array with empty player key 
 
var infoArray = [{ 
 
    "players": [] 
 
}]; 
 
// set the player key to a var 
 
var mykey = 'players'; 
 

 
// for each player 
 
$(".player").each(function() { 
 
    var el = infoArray[0]; 
 
    el[mykey].push($(this).text()); 
 
}); 
 

 
//show the resulting json 
 
$("#list").html(JSON.stringify(infoArray));
pre { 
 
    word-wrap:break-word; 
 
    padding:10px; 
 
    margin:10px; 
 
    background:#eee; 
 
    line-height: 1.7 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li class="player">James</li> 
 
    <li class="player">Emma</li> 
 
    <li class="player">Vincent</li> 
 
</ul> 
 
<h3>JSON result</h3> 
 
<pre id="list"></pre>

0

這裏的一個小錯誤,你infoArray應該是exapmle對象:在此之後

let info = { 
    "players": [] 
}; 

你可以把有項目,如:

info.players.push('New item'); 
0

刪除{}

$(".player").each(function() { 
    infoArray[mykey].push(
     // add the player's name to the key 
     $(this).text() 
    ); 
}); 
相關問題