簡體   English   中英

使用下划線查找和替換對象屬性值

[英]Find and replace object property value using underscore

假設我有一個json,如下所示。如何根據鍵status將json status替換inactive status

關鍵字:替換,下划線

{
    "id": "0001",
    "name": "Test",
    "status": "active"
}

您可以_.each()使用_.each()

_.each(YourArray, function(p){
    if(p.status === "active") p.status = "inactive";
    // or
    p.status = p.status === "active" ? "inactive" : p.status;
});

但是,為什么要在此任務中使用下划線 您可以使用“香草” js來解決它:

for(var i = 0,  l = YourArray.length; i < l; i++){
    if(YourArray[i].status === "active") YourArray[i].status = "inactive";
}

或使用Array.prototype.forEach()

YourArray.forEach(function(p){
    if(p.status === "active") p.status = "inactive";
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM