Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new object in JSON using jQuery or JavaScript?

Tags:

json

jquery

I want to add new obj of JSON like:

    "128": {
        "Msg": [{
            "me": "hi"
        }, {
            "user": "hello"
        }, {
            "me": "whtup"
        }]
    }

In the exist JSON object Example of JSON :

{
    "188": {
        "Msg": [{
            "me": "hi"
        }, {
            "user": "hello"
        }, {
            "me": "ki chal riha hai"
        }]
    },
    "123": {
        "Msg": [{
            "me": "hi"
        }, {
            "user": "hello"
        }, {
            "me": "whtup"
        }]
    },
    "128": {
        "Msg": [{
            "me": "hi"
        }, {
            "user": "hello"
        }, {
            "me": "whtup"
        }]
    }
like image 279
pargan Avatar asked Apr 02 '12 05:04

pargan


1 Answers

JSON stands for JavaScript object notation. So, it's nothing but an object ( actually a subset of object ) in javascript.

So, actually you want to add an object in existing javascript object.

Also, jQuery is nothing but a library (collections of different javascript functions to ease selecting dom elements, ajax functions, and some other utilities)

Coming back to your question,

If this is your existing object,

var obj = {
    "188": {
        "Msg": [{
            "me": "hi"
        }, {
            "user": "hello"
        }, {
            "me": "ki chal riha hai"
        }]
    },
    "123": {
        "Msg": [{
            "me": "hi"
        }, {
            "user": "hello"
        }, {
            "me": "whtup"
        }]
    },
    "128": {
        "Msg": [{
            "me": "hi"
        }, {
            "user": "hello"
        }, {
            "me": "whtup"
        }]
    }
}

You can add

  var objToAdd =  {
            "Msg": [{
                "me": "hi"
            }, {
                "user": "hello"
            }, {
                "me": "whtup"
            }]
        }

by,

obj["128"] = objToAdd;

Now, your obj is,

{
        "188": {
            "Msg": [{
                "me": "hi"
            }, {
                "user": "hello"
            }, {
                "me": "ki chal riha hai"
            }]
        },
        "123": {
            "Msg": [{
                "me": "hi"
            }, {
                "user": "hello"
            }, {
                "me": "whtup"
            }]
        },
        "128":{
            "Msg": [{
                "me": "hi"
            }, {
                "user": "hello"
            }, {
                "me": "whtup"
            }]
        }
    }
like image 146
Jashwant Avatar answered Sep 29 '22 23:09

Jashwant