How to check if a JSON key has unique values in a JSON file using javascript? -


i have json file like(for example) :

"fields": { "asset": {     "values": [{             "asset": {                 "id": "info_text",                 "type": "text",                 "value": "abcd"             }         },          {             "asset": {             "id": "info_input",             "type": "input",             "value": "abcde"             }         }     ] } } 

how can iterate on values of "id" , check if unique or not in javascript?

here complete demo without additional library, can find if key/value pair unique in json object , how many occurences found :

var jsondata = {    "fields": [      {        "asset": {          "id": "info_input",          "values": [            {              "asset": {                "id": "info_text",                "type": "text",                "value": "abcd"              }            },            {              "asset": {                "id": "info_input",                "type": "input",                "value": "abcde"              }            },            {              "asset": {                "id": "info_input",                "type": "input",                "value": "abcde"              }            }          ]        }      }    ]  }    function findkeyvaluecount(key, value, obj) {  	var count = 0;  	var keys = object.keys(obj);  	keys.foreach(function(k) {  		var v = obj[k];  		if(typeof v === 'object') {  			count += findkeyvaluecount(key, value, v)  		}  		else if(k === key && v === value) {  			count += 1;  		}  	});  	return count;  }    function isunique(key, value, obj) {  	return findkeyvaluecount(key, value, obj) === 1;  }      console.log(findkeyvaluecount('id', 'info_text', jsondata));  // -> 1    console.log(findkeyvaluecount('id', 'info_input', jsondata));  // -> 3    console.log(findkeyvaluecount('value', 'abcde', jsondata));  // -> 2    console.log(findkeyvaluecount('xxx', 'yyy', jsondata));  // -> 0    console.log(isunique('id', 'info_input', jsondata));  // -> false    console.log(isunique('id', 'info_text', jsondata));  // -> true

have fun !


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -