Operation of adding and deleting arrays

Source: Internet
Author: User
Tags parse string

To do batch data entry needs to be in the JSON array to increase the deletion check operation, splice is still very powerful record how to use.

var lang = ["PHP", "Java", "JavaScript"];

Delete
var removed = Lang.splice (2,1);
Console.log (lang); Php,javascript
Console.log (removed); Java, returning the deleted item
Insert
var insert = Lang.splice (0,0, "ASP"); Insert starting from No. 0 position
alert (insert); Returns an empty array
Console.log (lang); Asp,php,javascript
Replace
var replace = Lang.splice ("C #", "Ruby"); Delete one item, insert two items
alert (lang); Asp,c#,ruby

Console.log (replace); PHP, returning Deleted Items



In addition, a number of JSON additions and deletions are also affixed, alternate:

/**
* JSON object operation, additions and deletions
*
* @authorLellansin
* @blogWww.lellansin.com
* @version 0.1
*
* Solve some common problems
* Get/set solve the problem of no node interruption when getting and setting
* Create creates a multilevel node and overwrites the new value if it exists
* Delete Deletes the node and its child nodes
* Print_r formatted output object (for debugging purposes)
* See the bottom of the example
*/


function Json () {


}


/**
* Get a node in a JSON object
* For example: Json.get (Data, ' Country ', ' province ', ' City ');
* Results return data[' country ' [' Province '] [' City ']
* None returns False
*/
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
* For 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 nodes in JSON objects (overwrite values if present)
* For example: obj.create (data, ' Add ', ' hello ', ' test ', 120);
* Add 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 in a JSON object
* For example: Obj.delete (Prods, ' Grade ', ' 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;
}
}


/**
* Returns the string form of the JSON object (encapsulates the ECMAScript library function)
*/
Json.prototype.getStr = function (obj) {
return json.stringify (obj);
}


/**
* Parse string return JSON object (encapsulates ECMAScript library function)
*/
Json.prototype.getJson = function (str) {
return Json.parse (str);
}


/**
* Formatted 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 point the parameter floor is the penultimate, plus 1 is the last
Obj[tmpkey] = Args[floor + 1];
Console.log ("Success set, 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;
}
}
}
}
Node does not exist, create 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 + '} ';
};


Malicious code may be executed when parsing third-party JSON data using eval
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;
}
}






/**
* Usage Examples
*/


var data = {};


var prods = {
' Name ': ' Alan ',
' Grade ': {
' Chinese ': 120,
' Math ': 130,
' Competition ': {
' NOI ': ' First Prize '
}
}
};
/*
var json = new JSON ();


Console.log ("Get node 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", "Get No Nodes"));False a node that does not return false


Console.log ("Set node in JSON");
Console.log (Json.set (data, "ENTRY", "Fa_token_invalid", 1234)); TrueSet success
Console.log (Json.get (data, "ENTRY", "Fa_token_invalid"));1234 Get the node you just set
Console.log (Json.set (data, "ENTRY", "Test settings no Nodes", 1234)); FalseSetup failed


Console.log ("Create a new JSON node");
var prods = {
' Name ': ' Alan ',
' Grade ': {
' Chinese ': 120,
' Math ': 130,
' Competition ': {
' NOI ': ' First Prize '
}
}
};
Console.log (Json.create (Prods, ' create ', ' hello ', ' test ', 120));True
Console.log (Json.create (Prods, ' create ', ' hello ', ' test2 ', ' through ')); True


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


Console.log ("Delete node");
Console.log (Json.delete (Prods, ' Grade ', ' math '));True
Console.log (Json.delete (Prods, ' Grade ', ' competition '));True
Console.log (Json.delete (Prods, ' Grade ', ' Delete No Nodes ')); False
Json.print_r (prods);
*/


Operation of adding and deleting arrays

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.