Install npm package
npm i great-jsutils --save
Import api
import {JsUtilsApi, ArrayUtils, Base64, TimeUtils,StringUtils } from "great-jsutils/index";
Example 1: String removal
//String removal: the first parameter is the array to be operated, and the second parameter is the string to be removed testArray(){ let arr=["a","b","c"]; ArrayUtils.remove(arr,"b"); console.log(arr.join(","));//a,c }
Example 2: object removal
//Object removal: the first parameter is the array to be operated, the second parameter is the object to be removed, and the primary key of the third object testArray(){ let objArr=[{"id":"1","name":"Zhao Yun"},{"id":"2","name":"Zhu Geliang"}]; ArrayUtils.remove(objArr,{"id":"2"},"id"); console.log(JSON.stringify(objArr));//[{"id":"1","name": "Zhao Yun"}] }
Example 3: object key substitution in array
//Replace the key of the object in the array, for example, replace the source data with [{"name": "Zhang San"}] and [{"text": "Zhang San"}]
testArray(){ let datas=[{"name":"Zhang San","sex":"1"}]; let keys={"id":"key"}; let result=ArrayUtils.updateKey(data,keys); console.log(result);//[{"text": "Zhang San"}] }
Example 4: replace the key of the object in the array and add new attributes
//Replace the key of the object in the array, for example, replace the source data with [{"name": "Zhang San", "age: 80}] with [{" text ":" Zhang San "," age: 80, "agegroup": "elderly"}];
//This is to add new attributes according to some value characteristics testArray(){ let datas=[{"name":"Zhang San","sex":"1"}]; let keys={"name":"text"}; let result=ArrayUtils.updateKey(data,keys,function(){ if(data["age"]>75){ return {"ageGroup":"Aged"}; } }); console.log(result);//[{"text": "Zhang San", "age":80,"ageGroup": "the elderly"}]; }
Example 5: object key replacement in array, including child nodes
function testArray(){ let data=[{"id":"id-A","type":"1","children":[ {"id":"id-A01","type":"2","children":[ {"id":"id-A01-01","type":"3"} ]}, {"id":"id-A03","type":"3"} ]}]; let keys={"id":"key"}; let result=ArrayUtils.updateKey(data,keys,function (data) { if(typeof data == "object"){ if(!data["children"] || data["children"]==null ||data["children"]["lenght"]==0){ return {"isLeaf":true}; }else{ return {"childNum":data["children"]["length"]}; } } }); console.log(result); } testArray();
Example 6: verify array
ArrayUtils.validArray(datas)
Example 7: add child data to tree data
Append a new child node to the specified node
function testArray(){ let data=[{"id":"id-A","type":"1","children":[ {"id":"id-A01","type":"2","children":[ {"id":"id-A01-01","type":"3"} ]}, {"id":"id-A03","type":"3"} ]}]; let child={"id":"id-A03-01","pid":"id-A03"}; let newData=ArrayUtils.addByParentId(data,child,"pid","id","children"); console.log(result); }