Add, delete, modify, and query an array

Source: Internet
Author: User

Add, delete, modify, and query an array

During batch data input, you need to add, delete, modify, and query arrays in json. splice is a powerful method to record the usage.

Var lang = ["php", "java", "javascript"];

// Delete
Var removed = lang. splice (2, 1 );
Console. log (lang); // php, javascript
// Console. log (removed); // java, return the deleted item
// Insert
Var insert = lang. splice (0th, "asp"); // insert data from locations
// Alert (insert); // returns an empty array
Console. log (lang); // asp, php, javascript
// Replace
Var replace = lang. splice (, "c #", "ruby"); // delete one item and insert two items
// Alert (lang); // asp, c #, ruby

Console. log (replace); // php, return the deleted item



In addition, the addition, deletion, modification, and query of multiple json files are also attached:

/**
* Json object operations: add, delete, modify, and query
*
* @ Author lellansin
* @ Blog www.lellansin.com
* @ Version 0.1
*
* Solve some common problems
* Get/set solves the problem of no node interruption when obtaining and setting.
* Create can create a multi-level node. If it exists, it overwrites the new value.
* Delete a node and Its subnodes
* Print_r format the output object (for debugging)
* For the instance, see the bottom.
*/


Function Json (){


}


/**
* Get a node in the Json object
* Example: json. get (Data, 'country', 'vince ', 'city ');
* If the result is returned, Data ['country'] ['vince '] ['city'] is returned.
* If none, false is returned.
*/
Json. prototype. get = function (obj, key ){
Var args = this. get. arguments;
Var result = obj;


For (var I = 1; I <args. length; I ++ ){
Result = result [args [I];
If (result = undefined ){
Return false;
};
};
Return result;
};


/**
* Set a node in the Json object
* Example: obj. set (data, "ENTRY", "FA_TOKEN_INVALID", 1234 );
* Set data ['entry '] ['fa _ token_invalid'] To 1234.
* Success: true; Failure: false
*/
Json. prototype. set = function (obj, key ){
Var args = this. set. arguments;
If (ergodic_set (obj, args, 1 )){
Return true;
} Else {
Return false;
}
}


/**
* Create a node in the Json object (overwrite the value if any)
* Example: obj. create (data, 'add', 'Hello', 'test', 120 );
* Add the data ['create'] ['hello'] ['test'] node and set the value to 120.
* Success: true; Failure: false
*/
Json. prototype. create = function (obj, key ){
Var args = this. create. arguments;
If (ergodic_create (obj, args, 1 )){
Return true;
} Else {
Return false;
}
}


/**
* Delete a node from a Json object
* Example: obj. delete (prods, 'grad', 'Math ');
* Success: true; Failure: false
*/
Json. prototype. delete = function (obj, key ){
Var args = this. delete. arguments;
If (ergodic_delete (obj, args, 1 )){
Return true;
} Else {
Return false;
}
}


/**
* Return the string form of the Json object (encapsulate the ECMAScript library function)
*/
Json. prototype. getStr = function (obj ){
Return JSON. stringify (obj );
}


/**
* Parse the string and return a Json object (encapsulate the ECMAScript library function)
*/
Json. prototype. getJson = function (str ){
Return JSON. parse (str );
}


/**
* Format the output Json object.
*/
Json. prototype. print_r = function (obj ){
Console. log ("{")
Ergodic_print (obj ,"");
Console. log ("}")
}


Function ergodic_print (obj, indentation ){
Var indent = "" + indentation;
If (obj. constructor = Object ){
For (var p in obj ){
If (obj [p]. constructor = Array | obj [p]. constructor = Object ){
Console. log (indent + "[" + p + "] =>" + typeof (obj) + "");
Console. log (indent + "{");
Ergodic_print (obj [p], indent );
Console. log (indent + "}");
} Else if (obj [p]. constructor = String ){
Console. log (indent + "[" + p + "] => '" + obj [p] + "'");
} Else {
Console. log (indent + "[" + p + "] =>" + obj [p] + "");
}
}
}
}


Function ergodic_set (obj, args, floor ){
If (obj. constructor = Object ){
For (var tmpKey in obj ){
If (tmpKey = args [floor]) {
If (floor <args. length-2 ){
Return ergodic_set (obj [tmpKey], args, floor + 1 );
} Else {
// At this time, the parameter floor is the second to the last, and the value of 1 is the last one.
Obj [tmpKey] = args [floor + 1];
Console. log ("set successfully, return true ");
Return true;
}
}
}
}
}


Function ergodic_create (obj, args, floor ){
If (obj. constructor = Object ){
For (var tmpKey in obj ){
If (tmpKey = args [floor]) {
If (floor <args. length-2 ){
Return ergodic_create (obj [tmpKey], args, floor + 1 );
} Else {
Obj [tmpKey] = args [floor + 1];
Return true;
}
}
}
}
// The node does not exist. Create a new node.
If (floor <args. length-1 ){
Var jsonstr = getJsonFormat (args [args. length-1]);


For (var I = args. length-2; I> floor; I --){
Jsonstr = '{"' + args [I] + '":' + jsonstr + '}';
};


// When parsing third-party Json data using eval, malicious code may be executed
// Var node = eval ('+ jsonstr + ')');
Var node = JSON. parse (jsonstr );
Obj [args [floor] = node;
Return true;
}
}


Function ergodic_delete (obj, args, floor ){
If (obj. constructor = Object ){
For (var tmpKey in obj ){
If (tmpKey = args [floor]) {
If (floor <args. length-1 ){
Return ergodic_delete (obj [tmpKey], args, floor + 1 );
} Else {
Delete obj [tmpKey];
Return true;
}
}
}
}
}




Function getJsonFormat (param ){
If (param. constructor = String ){
Return '"' + param + '"';
} Else {
Return param;
}
}






/**
* Use instances
*/


Var data = {};


Var prods = {
'Name': 'Alan ',
'Grad ':{
'China': 120,
'Math': 130,
'Computing ':{
'Noi': 'First Prize'
}
}
};
/*
Var json = new Json ();


Console. log ("Get nodes in Json ");
Console. log (json. get (data ));
Console. log (json. create (data, "0 ",""));
Console. log (json. set (data, "0", prods ));
Console. log (json. create (data, "1 ",""));
Console. log (json. set (data, "1", prods ));
Console. log (json. create (data, "2 ",""));
Console. log (json. set (data, "2", prods ));
Console. log (json. get (data ));
Json. print_r (data );*/
/*
Console. log (json. get (data, "OK"); // 200
Console. log (json. get (data, "ENTRY", "FA_TOKEN_INVALID"); // 1001
Console. log (json. get (data, "TEST", ""); // false if no node is returned, false


Console. log ("set nodes in Json ");
Console. log (json. set (data, "ENTRY", "FA_TOKEN_INVALID", 1234); // true
Console. log (json. get (data, "ENTRY", "FA_TOKEN_INVALID"); // 1234 obtain the node you just set
Console. log (json. set (data, "ENTRY", "test node not set", 1234); // false setting failed


Console. log ("Creating a New Json node ");
Var prods = {
'Name': 'Alan ',
'Grad ':{
'China': 120,
'Math': 130,
'Computing ':{
'Noi': 'First Prize'
}
}
};
Console. log (json. create (prods, 'create', 'Hello', 'test', 120); // true
Console. log (json. create (prods, 'create', 'Hello', 'test2', 'pass'); // true


Console. log ("formatting output node ");
Json. print_r (prods );


Console. log ("delete node ");
Console. log (json. delete (prods, 'grad', 'Math'); // true
Console. log (json. delete (prods, 'grad', 'computing'); // true
Console. log (json. delete (prods, 'grade ', 'delete nodes not exists'); // false
Json. print_r (prods );
*/


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.