简体   繁体   中英

How can I push elements into an array that's within an object? (javascript/jQuery)

How can I push data stored within a list into a specific array ("items: [ ]") that's nested within an object?

  var obj = {
    name: customerName,
    items: [],
    price: [] }


     <ul>
        <li>Blah blah blah<li>
    </ul>
obj.items.push(1);
obj.price.push(2);

Will result in:

{
    name: 'someName',
    items: [ 1 ],
    price: [ 2 ] 
}

To push data from your list items into the items Array you could do the following:

<!DOCTYPE html>

<html>
    <head>
        <meta charset="utf-8"/>

        <title>jQuery list</title>

        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>

    <body>
        <ul>
            <li>one</li>
            <li>two</li>
            <li>three</li>
        </ul>

        <script>
            $(document).ready(function () {
                var obj = {
                    items: []
                };

                $('li').each(function () {
                    // Extract the text node from the list item.
                    var textNode = $(this).text();

                    obj.items.push(textNode);
                });

                console.log(obj.items); // [ "one", "two", "three" ]
            });
        </script>
    </body>
</html>

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