3

Say I have an array such as this in Javascript:

var cars = { vendor: [ { type: [ 'camry', 'etc' ] } ] } 

In Javascript what command can I use to add an item to type... For example if I wanted to have a text box that a user can place text into and then hit a button that will add the item into the array. The item that would be added would need to be placed in with the same items as "camry" and "etc". Thanks!

0

4 Answers 4

17

Try something like

cars.vendor[0].type.push("foo");

Where "foo" is your data to add.

Sign up to request clarification or add additional context in comments.

Comments

7

You can add items to the array using the push() method to add to the end, or unshift() to add to the front.

var newValue = 1234;

cars.vendor[0].type.push(newValue);

The event handler could then be bound using something similar to this;

$("yourSelector").on("click", function(){
    var value = $("input").val();

    cars.vendor[0].type.push(value);
});

Please bear in mind that what you have is not JSON at all. It's a nested structure of JavaScript Objects and Arrays, declared using literal syntax. See Javascript object Vs JSON for more info.

Comments

1

Sample Test example for this problem as below:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
    var cars = {
        "vendor": [
            {
                "type": [
                    "camry",
                    "maruti",
                    "bmw"
                ]
            }
        ]
    };
    $("#add").click(function(){
        var types=cars["vendor"][0]["type"];
        types.push($("#json").val());
        $("#types").html(types.toString());
    });
});
</script>
</head>
<body>
<input type="text" id="json" name="json"/>
<input type="button" id="add" name="add" value="ADD"/>
<div id="types" style="margin:10px;border:1px dotted green;width:400px;"></div>
</body>
</html>

1 Comment

Awakening the dinosaur here but what if there wasn't a "type" defined yet, meaning the user first landed on the page and wanted to dynamically build the vendor object?
-1

You can try something like given below

var cars = { vendor: [ { type: [ 'camry', 'etc' ] } ] } ;
cars.vendor[0].type[2]="abc";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.