簡體   English   中英

如何遍歷對象數組並根據 JavaScript 中的條件添加新的對象鍵?

[英]How to loop through array of objects and add new object key based on condition in JavaScript?

我有以下對象數組:

[{"id":0,"name":"Katy","age":22},
{"id":2,"name":"Lucy","age":12},
{"id":1,"name":"Jenna","age":45},
{"id":3,"name":"Ellie","age":34}]

我需要在對象中添加另一個鍵( PaymentCategory ),其中 ID 最低的對象添加值為“Cash”的鍵,ID 最高的鍵為“Card”,以及介於“Cheque”之間的所有內容; 該數組還必須按 ID 排序。

因此所需的輸出將是:

[{"PaymentCategory":"Cash","id":0,"name":"Katy","age":22},
{"Payment Category":"Cheque","id":1,"name":"Jenna","age":45},
{"Payment Category":"Cheque","id":2,"name":"Lucy","age":12},
{"Payment Category":"Card","id":3,"name":"Ellie","age":34}]

我們怎樣才能以最有效的方式實現這個結果,即最少的迭代次數,最高的性能?

這是我嘗試過的:

const min = array.reduce((prev,curr)=> prev.id<curr.id?prev:curr)
  const max = array.reduce((prev,curr)=> prev.id>curr.id?prev:curr)
  min.PaymentCategory = "Cash"
  max.PaymentCategory = "Credit"
  const result =[min, max]

問題在於:

  1. 我循環遍歷它兩次,一次用於max ,一次用於min
  2. 我如何獲得“中間”值?

我認為如果您簡單地使用Array.prototype.sort對數組進行就地排序,使用排序謂詞函數,除了決定排序順序,還添加“默認”“PaymentCategory”鍵,然后在排序數組中的第一個和最后一個對象上為“PaymentCategory”分配正確的值:

array.sort((a, b) => {
    a.PaymentCategory = b.PaymentCategory = "Cheque"; /// You can also test with the `if(!a.PaymentCategory) a.PaymentCategory = "Cheque";` statement instead, but correctness may depend on the sorting algorithm the platform employs.
    return a.id - b.id; /// Or `(a.id < b.id) ? -1 : 1`  but the former is simpler and typically just as fast so better in all regards, IMO
});
array[0].PaymentCategory = "Cash";
array.at(-1).PaymentCategory = "Credit";

上面在排序期間分配了“默認”付款類別,因為分配可以說比分配前的測試便宜。 但是在排序之后,由於數組現在已經按“id”排序,第一個元素應該是具有最小“id”的元素和具有最大“id”的最后一個元素,代碼段為其分配了正確的類別。 array.at(-1)替代版本是array[array.length - 1]

由於您需要對“id”進行排序,因此無論如何您都需要對數組進行實際排序——例如,使用前面提到的sort (這可能比實現自己的sort要快得多),並給出堆排序的方式例如,算法具有最差的時間復雜度 $O(n * log(n))$,除了實際排序的成本之外,您幾乎沒有支付任何額外費用——當然比運行reduce兩次的次數更少,而您甚至不需要之后得到一個排序的數組。 這意味着你必須排序,所以排序,但支付類別的分配幾乎是“免費”完成的,因為它是一個不變的成本操作,而sort你的數組sort排序。

PS這是可能的-我沒有測試這一點,它可以取決於排序算法正在使用-這用於任一分配“PaymentCategory” ab是足夠排序謂詞功能的呼叫期間,而不是為這兩種分配, . 這將依賴於實施的具體排序算法sort ,這就是為什么在兩個我給你類別ab ,留在安全方面。

你可以這樣做

 const array =[{"id":0,"name":"Katy","age":22}, {"id":2,"name":"Lucy","age":12}, {"id":1,"name":"Jenna","age":45}, {"id":3,"name":"Ellie","age":34}] const arrayLength= array.length const newA=array.map( (element,index) => { if (index===0) return {"PaymentCategory":"Cash", ...element} else if ( index===arrayLength-1 )return {"PaymentCategory":"Card", ...element} else return {"PaymentCategory":"Cheque", ...element}})

檢查數組中的映射方法以了解更多信息: https : //learnjsx.com/category/2/posts/es6-mapFunction

以下提供的方法很簡單,首先按升序 ( .sort((a, b) => a.id - b.id) ) 對淺數組副本 ( [...sampleData] ) 的項目進行sort id值。

最后的任務確實以創建淺拷貝( { ...item } )的方式map每個(排序的)項目,此外還會創建一個'Payment Category'條目,其中第一個項目( idx === 0 )被分配'Cash'值,最后一項 ( (idx === arr.length - 1) ) 被分配了'Card'值,所有其他被分配了'Cheque'值。

整個方法不會改變最初提供的數據......

 const sampleData = [ { id: 0, name: "Katy", age: 22 }, { id: 2, name: "Lucy", age: 12 }, { id: 1, name: "Jenna", age: 45 }, { id: 3, name: "Ellie", age: 34 }, ]; console.log( 'mapped `sampleData` items ...', [...sampleData] .sort((a, b) => a.id - b.id) .map((item, idx, arr) => ({ ...item, 'Payment Category': ((idx === 0) && 'Cash') || ((idx === arr.length - 1) && 'Card') || 'Cheque', })) ); console.log('unmutated `sampleData` ...', sampleData);
 .as-console-wrapper { min-height: 100%!important; top: 0; }

上述方法以一種更具可讀性的方式......

 const copyItemAndAugmentPaymentCategory = (item, idx, arr) => ({ ...item, 'Payment Category': ((idx === 0) && 'Cash') || ((idx === arr.length - 1) && 'Card') || 'Cheque', }); const compareItemIdPrecedenceAscending = (a, b) => a.id - b.id; console.log( [ { id: 0, name: "Katy", age: 22 }, { id: 2, name: "Lucy", age: 12 }, { id: 1, name: "Jenna", age: 45 }, { id: 3, name: "Ellie", age: 34 }, ] .sort(compareItemIdPrecedenceAscending) .map(copyItemAndAugmentPaymentCategory) );
 .as-console-wrapper { min-height: 100%!important; top: 0; }

暫無
暫無

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

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