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!

Matt
  • 74,352
  • 26
  • 153
  • 180
amlane86
  • 668
  • 4
  • 15
  • 24

4 Answers4

17

Try something like

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

Where "foo" is your data to add.

Matt
  • 74,352
  • 26
  • 153
  • 180
jack
  • 1,317
  • 1
  • 14
  • 21
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.

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
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>
Umesh Patil
  • 10,475
  • 16
  • 52
  • 80
  • 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? – HPWD Oct 03 '17 at 17:45
-1

You can try something like given below

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