开发者

Builtin Query Capabilities in JSON using Javascript or JQuery

开发者 https://www.devze.com 2023-01-05 09:11 出处:网络
I am looking query the JSON data based on some where conditions for ex. list the person names whose cell no is 777-777-7777.

I am looking query the JSON data based on some where conditions for ex. list the person names whose cell no is 777-777-7777.

pl let me know what are query capabilities in JSON.

var json = [{
    "name": "senthil",
    "Phoneno": [{
        "Home": "111-111-1111"
      },
      {
        "Cell": "222-222-2222"
      },
      {
        "Office": "333-333-3333"
      }
    ],
    "City": "Hartford"
  },
  {
    "name": "kumar",
    "Phoneno": [{
        开发者_运维问答"Home": "444-555-6666"
      },
      {
        "Cell": "777-777-7777"
      },
      {
        "Office": "888-888-8888"
      }
    ],
    "City": "Austin"
  },
];


var people = json.filter(function(el) 
             { 
               return el.Phoneno.some(function(number) 
                      {
                        return number.Cell == "777-777-7777"; 
                      }); 
             });

This uses the Array.filter and Array.some functions from ECMAScript 5. filter returns an array of the elements that pass a test. some returns true if any element in an array passes the test.

For browsers that don't support it, you can use the code at MDC.

This will almost certainly not be faster than the obvious for-loop approach.

As a note, if every person can have up to one phone number per type, a simpler representation would be:

"Phoneno": { "Home": "111-111-1111",
             "Cell": "222-222-2222",
             "Office": "333-333-3333" 
           }

Also, JSON technically refers to the text representation, not actual JavaScript objects.

0

精彩评论

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