Yasin Patel Yasin Patel - 2 months ago 10
JSON Question

How insert element into json object using jquery/javascript?

I am Creating javascript variable From PHP associative array as Below :

var frontdata= '<?php echo json_encode(Yii::$app->mycomponent->getFrontActorID());?>';
frontdata=$.parseJSON(frontdata);


It gives me Following output :


Object {1: "User", 9: "Driver", 10: "Waiter", 11: "WareHouse Keeper"}


Now I want to add one more record in object.

i.e. 12:"Admin"

So,it looks Like


Object {1: "User", 9: "Driver", 10: "Waiter", 11: "WareHouse
Keeper",12:"Admin"}


How to Do this using javascript or jQuery ?

I already Tried
JSON.stringify
and
frontdata.items.append
,but it is not working. or i don't know how to implement it.

Thanks

Answer

JSON Data in Javascript behave like Normal Javascript Objects or rather is (in essence) an Object. You could treat the JSON Data like You would any Normal JS Object and Here is how:

JAVASCRIPT:

<script type="text/javascript">

    var frontdata = {1: "User", 9: "Driver", 10: "Waiter", 11: "WareHouse Keeper"};

    // ADD THE NEW ENTRY(IES) TO THE JSON OBJECT:
    frontdata[12] = "Admin";
    frontdata[24] = "Chef";


    console.log(frontdata);
    // YIELDS:: 
    Object {
              1: "User", 
              9: "Driver", 
              10: "Waiter", 
              11: "WareHouse Keeper", 
              12: "Admin", 
              24: "Chef"
            }

</script>
Comments