溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

數(shù)組元素添加與刪除,包括樹結(jié)構(gòu)數(shù)據(jù)

發(fā)布時(shí)間:2020-07-31 07:56:57 來源:網(wǎng)絡(luò) 閱讀:177 作者:zhaoqingkaitt 欄目:web開發(fā)

安裝npm包

npm i?great-jsutils --save

導(dǎo)入api

import {JsUtilsApi, ArrayUtils, Base64, TimeUtils,StringUtils } from "great-jsutils/index";

示例1:字符串移除

 //字符串移除,第一個(gè)參數(shù)是被操作的數(shù)組,第二個(gè)參數(shù)是需要移除的字符串
testArray(){
    let arr=["a","b","c"];
    ArrayUtils.remove(arr,"b");
    console.log(arr.join(","));//a,c
}

示例2:對(duì)象移除

//對(duì)象移除,第一個(gè)參數(shù)是被操作的數(shù)組,第二個(gè)參數(shù)是需要移除的對(duì)象,第三個(gè)對(duì)象的主鍵
testArray(){
    let objArr=[{"id":"1","name":"趙云"},{"id":"2","name":"諸葛亮"}];
    ArrayUtils.remove(objArr,{"id":"2"},"id");
    console.log(JSON.stringify(objArr));//[{"id":"1","name":"趙云"}]
}

示例3:數(shù)組中的對(duì)象key替換

//數(shù)組中的對(duì)象key替換,例如源數(shù)據(jù)為[{"name":"張三"}]替換為[{"text":"張三"}]

testArray(){
    let datas=[{"name":"張三","sex":"1"}];
    let keys={"id":"key"};
    let result=ArrayUtils.updateKey(data,keys);
    console.log(result);//[{"text":"張三"}]
}

示例4:數(shù)組中對(duì)象key替換,并增加新的屬性

//數(shù)組中對(duì)象key替換,例如源數(shù)據(jù)為[{"name":"張三","age":80}]替換為[{"text":"張三","age":80,"ageGroup":"老年人"}];

 //這里是根據(jù)某些值特征,增加新的屬性
testArray(){
    let datas=[{"name":"張三","sex":"1"}];
    let keys={"name":"text"};
    let result=ArrayUtils.updateKey(data,keys,function(){
        if(data["age"]>75){
            return {"ageGroup":"老年人"};
        }
    });
    console.log(result);//[{"text":"張三","age":80,"ageGroup":"老年人"}];
}

示例5:數(shù)組中對(duì)象key替換,含有子節(jié)點(diǎn)

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();

示例6:驗(yàn)證是否為數(shù)組

ArrayUtils.validArray(datas)

示例7:樹狀數(shù)據(jù)添加子數(shù)據(jù)

向指定節(jié)點(diǎn),追加新的子節(jié)點(diǎn)

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);
}

?

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI