我想使用JQuery将以下XML
代码转换为对象
这就是我的XML外观:
<league name="German 1st Bundesliga>
<club name="FC Bayern München" coach="Ancelotti" stadium="Allianz Arena" clubId="1000" />
<club name="Borussia Dortmund" coach="Tuchel" stadium="Signal Iduna Park" clubId="1001" />
<club name="Borussia Mönchengldabach" coach="Schubert" stadium="Borussia-Park" clubId="1002" />
<club name="FC Schlke 04" coach="Weinzierl" stadium="Veltins-Arena" clubId="1003" />
</league>
这是我创建对象的代码
var $leagueNode = $(response).find('league');
var clubList = [];
for(var i=0; i < $leagueNode.children().length; i++){
console.log($leagueNode.children()[i]);
var $clubNode = $($leagueNode.children()[i]).find('club');
var club = {};
club.clubid = $clubNode.attr('clubid');
club.name = $clubNode.attr('name');
club.coach = $clubNode.attr('coach');
club.stadium= $clubNode.attr('stadium');
console.log(club);
}
打印到控制台的对象显示所有属性的undefined
。我的代码出了什么问题?
答案 0 :(得分:2)
要执行您需要的操作,您可以使用map()
创建一个对象数组。试试这个:
var $leagueNode = $('<league name="German 1st Bundesliga"><club name="FC Bayern München" coach="Ancelotti" stadium="Allianz Arena" clubId="1000" /><club name="Borussia Dortmund" coach="Tuchel" stadium="Signal Iduna Park" clubId="1001" /><club name="Borussia Mönchengldabach" coach="Schubert" stadium="Borussia-Park" clubId="1002" /><club name="FC Schlke 04" coach="Weinzierl" stadium="Veltins-Arena" clubId="1003" /></league>');
var obj = $leagueNode.find('club').map(function() {
var $club = $(this);
return {
clubid: $club.attr('clubid'),
name: $club.attr('name'),
coach: $club.attr('coach'),
stadium: $club.attr('stadium'),
};
}).get();
console.log(obj);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;