1

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>
2
  • 3
    obj.items.push() Commented Aug 29, 2015 at 17:23
  • 1
    obj.items.push('something') Commented Aug 29, 2015 at 17:24

1 Answer 1

3
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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I have multiple <li> items in my list - and when I use this method to add them into my "items" array - it comes out as one long string instead of separate items in my array. How can I fix this?
@YNinNY do you mean you want to push the text node of your list items into the items Array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.