簡體   English   中英

檢查並添加數組對象中的屬性

[英]Check and add for property in object of arrays

我在下面有一個非常具體的格式細節的對象/輸出:

result = 
AB: [ 0:{Name: "Tom", team:"Spirit", position: "Defender", score: 22 }
    1:{Name: "Paul", team:"Vikings", position: "center" }
    2:{Name: "Jim", team:"United", position: "Wing", }
    3:{Name: "Greg", team:"Crusaders", position: "Fullback", score: 54}
    4:{Name: "Tim", team:"Vikings", position: "Fullback", score: 77 }
    ]
CD: [0:{...},1:{...},2:{...},3:{...},4:{...}]
EF: [0:{...},1:{...},2:{...},3:{...},4:{...}]
GH: [0:{...},1:{...},2:{...},3:{...},4:{...}]

結果有嵌套數組。 在某些輸出上, score的屬性不存在,但我需要它 - 如果它不存在,我需要將它默認添加為score:""如果它在那里,那么就不要管它。

我已經能夠添加score的屬性,但只能在結果對象的頂層,例如

...
    GH: [0:{...},1:{...},2:{...},3:{...},4:{...}]
    score:""

經過

 if(result.hasOwnProperty("score")) {
     alert('Item has already that property');
 } else {
     result.score = "" ;
 }

我可以通過(下面)定位特定路徑,但我想將其應用於所有路徑:

 if(finalResult['AB'][1].hasOwnProperty("durabilityScore")) {
    alert('Item has already that property');
} else {
    finalResult['AB'][1].durabilityScore = 'value';
}

如果有幫助,我正在使用 Lodash。 謝謝

您可以迭代對象和數組的值。 然后檢查該屬性是否存在,如果不存在則賦值。

此解決方案不會覆蓋虛假值( 0''falseundefinednull ),如果使用默認檢查,則會發生這種情況,例如

o.score = o.score || ''

 var result = { AB: [{ Name: "Tom", team:"Spirit", position: "Defender", score: 22 }, { Name: "Paul", team:"Vikings", position: "center" }, { Name: "Jim", team:"United", position: "Wing" }, { Name: "Greg", team:"Crusaders", position: "Fullback", score: 54 }, { Name: "Tim", team:"Vikings", position: "Fullback", score: 77 }] }; Object.values(result).forEach(a => a.forEach(o => 'score' in o || (o.score = ''))); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

暫無
暫無

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

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