开发者

how to add new set of values with property when json object already exist..using javascript

i already have json object..like this,

updates={
    mainUpdates:[{id:'1', inner:[{mid:'11',sub_domain:'a'},{mid:'12',sub_domain:'b'}]},
                 {id:'2', inner:[{mid:'21', sub_domain:'c'},{mid:'22',sub_domain:'d'}]} 
    ],
    msgCount:'2'
}

now i want add new values with its name(property) dynamically to the existing my json object. using javascrit... i want the exactly answer is look like

updates={
    mainUpdates:[{id:'1', inner:[{mid:'11',sub_domain:'a'},{mid:'12',sub_domain:'b'}]},
                 {id:'2', inner:[{mid:'21',sub_domain:'c'},{mid:'22',sub_domain:'d'}]}, 
                 {id:'3', inner:[{mid:'31',sub_domain:'e'},{mid:'22', sub_domain:开发者_JAVA技巧'f'}]} 
    ],
    msgCount:'3'
}

how i do


You can manipulate your update object directly something like this:

updates.mainUpdates.push({
   id:'3', 
   inner:[{mid:'31',sub_domain:'e'},{mid:'22', sub_domain:'f'}]
});
updates.msgCount = 3;

updates.mainUpdates is just a JavaScript array so you can add new objects to it using the push method. updates.msgCount is just a property so can be modified directly.

It might be better to encapsulate this kind of change in a helper method that keeps the msgCount in synch with the array (assuming that is what it is there for).

function addToUpdates(updates, newItem) {
   updates.mainUpdates.push(newItem);
   updates.msgCount = updates.mainUpdates.length;
}


Use jQuery extend function (Merge the contents of two or more objects together into the first object.):

Example: Merge two objects, modifying the first.

var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

$.extend(object1, object2);

Result:

object1 === {apple: 0, banana: {price: 200}, cherry: 97, durian: 100}

Your msgCount field is redundant, as you can use update.mainUpdates.length

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜