简体   繁体   中英

How to push HTML list vales to a single JSON key as an array in javascript

I'm trying to get the text values of a HTML list and then push them to a single key value in a JSON object. I was hoping the JSON contents would look like {"players": ["James","Emma","Vincent"]} . My current attempt is below.

 // 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> 

Couple of things:

1) No need for { } in push() function

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

2) Don't initialize value of key player as empty string "" , instead use empty array [] .

Also note that infoArray is a JSON array and not a JSON object.


 // 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> 

A little mistake here, your infoArray should be an object for exapmle:

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

after this you can push there items like:

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

remove {} :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM