簡體   English   中英

如何編輯對象數組?

[英]How to edit object array?

我想編輯JavaScript對象。

我有一個這樣的JavaScript對象

data_without_id = [
                   0: {id: 1, name: "Mary", age: null}
                   1: {id: 2, name: "Bob", age: 33}
                   2: {id: 1, name: "Kelly", age: 40}
                  ]

我想將此對象轉換為此

data_without_id = [
                   0: {id: 1, name: "Kelly", age: 40}
                   1: {id: 2, name: "Bob", age: 33}
                  ]

我需要做的是:

  1. id分組

  2. 獲得最新價值。

我嘗試使用Array.prototype.reduce() ,但無法獲得所需的結果...

使用reduce功能將如下所示:

該功能reduce了分組和功能Object.values用於提取值。

 let data_without_id = [ { id: 1, name: "Mary", age: null }, { id: 2, name: "Bob", age: 33 }, { id: 1, name: "Kelly", age: 40 }], result = Object.values(data_without_id.reduce((a, {id, name, age}) => { a[id] = {id, name, age}; return a; }, Object.create(null))); console.log(result) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以通過使累加器成為具有id鍵的對象來使用.reduce 這樣,您可以覆蓋任何先前看到的具有相同id對象,然后使用Object.values獲取對象數組:

 const data_without_id = [{id: 1, name: "Mary", age: null}, {id: 2, name: "Bob", age: 33}, {id: 1, name: "Kelly", age: 40}], res = Object.values(data_without_id.reduce((acc, obj) => (acc[obj.id] = obj, acc) , {})); console.log(res); 

您可以簡單地使用for/of循環創建數據的副本,其中最后一個具有特定ID的對象將始終是輸出數據中返回的對象。 這樣可以避免代碼的“分組”部分,但仍返回正確的數據。

 const data_without_id = [ { id: 1, name: "Mary", age: null }, { id: 2, name: "Bob", age: 33 }, { id: 1, name: "Kelly", age: 40 } ]; function lastId(arr) { const out = []; for (let obj of arr) { // If you don't create a copy of each object the returned // data will simply be contain _references_ to the original // data. Changes in the original data will be reflected // in the returned data out[obj.id - 1] = { ...obj }; } return out; } const lastIds = lastId(data_without_id); console.log(lastIds); 

暫無
暫無

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

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