开发者

Using JQuery to manipulate JSON Object

Can we use JQuery functions to manipulate and 开发者_如何学Csearch in JSON Object? Like if I have a big Object of type of array of this object:

Node 
{
    Name,
    Property1,
    Property2
}

can I use jquery function find to find a node with property Name as John? and similarly modify the contents as well??

edit: yes, I was actually looking for something like JLinq, Thank you


i think what you're looking for here is jLinq. its like linq, but its a jquery plugin. to do what you're asking about is really easy. it would be something like :

var matchingNodes = jlinq.from(data.Nodes).equals("Name", "John").select();

if you want only the first match try :

var firstMatch = jlinq.from(data.Nodes).equals("Name", "John").first();

and thats all there is to it. very quick and efficient, and very semantic, so its easy to maintain an understand the intent.


To find that node, you would loop through like so...

$.each(yourJson, function(i, node) {

    if (node.Name == 'John') {
        // Found it
        return false;
    }

});

This is O(n).


No, sorry. jQuery is meant for working with DOM nodes, or XML structures. If you want to search object hashes you need to do it manually. Even if jQuery had methods to do it, there isn't any "magic" that it can do to make things faster like it does with DOM searches -- there simply are no faster ways to search a hash than doing it recursively (unless you've pre-parsed it)

OMFG PEOPLE!!

Look, jQuery is not the be-all-end-all savior of everything JavaScript. Some things are just better in straight JS! What is so horrible about:

for(var i=0, l=ary.length; i<l; i++){
   if(ary[i].Name=='John'){
      // do something
      break;
   }
}

The answer you are "looking" for is simply:

$(ary).filter(function(){ return this.Name=='John'; });

Happy? It's going to be slower because you have nested function calls, it's going to be slower because it's going to iterate over every element instead of stopping.

But it uses jQuery.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜