簡體   English   中英

從對象數組 Javascript 創建嵌套的對象數組

[英]Create nested array of objects from array of objects Javascript

我有以下對象數組。 如何重塑數據以獲得預期的 Output?

let performanceReview = [ 
{ "name": "Sean", "Manager": "Joe", "Performance": 5}, 
{ "name": "John", "Manager": "Joe", "Performance": 9}, 
{ "name": "Paul", "Manager": "Joe", "Performance": 0}, 
{ "name": "Derek", "Manager": "Greg", "Performance": 10}, 
{ "name": "Lisa", "Manager": "Greg", "Performance": 10}, 
{ "name": "Julia", "Manager": "Donna", "Performance": 7}];

預計 Output

var Series = [ 
{Manager: "Joe", data: [["Sean", 5], ["John", 9], ["Paul", 0]]}, 
{Manager: "Greg", data: [["Derek", 10],["Lisa", 10]]}, 
{Manager: "Donna", data: [["Julia", 7]]}];

有人也可以幫助我了解他們解決問題的方法。

此解決方案將任務分為兩個步驟 (代碼可能更短,但這可能比試圖將所有邏輯壓縮到一個單行中更容易理解。)

  1. 使用Array.prototype.reduce ,我們可以創建一個 object ,其中每個屬性都有:
  • 經理的姓名作為鍵和
  • minions-with-ratings 的二維數組作為值
  1. 然后,使用for...in語法,我們可以將每個屬性轉換為獨立的 object 並將其推送到 output 數組中。

有關說明,請參閱代碼內注釋。

 // Main const originalArray = getOriginalArray(), obj = groupByManager(originalArray), output = formatFinalArray(obj); console.log(output); // We make an object because, unlike Arrays, they use named properties function groupByManager(input){ const obj = input.reduce( // 1st argument to `reduce` is a 'reducer' function (taking two args) // that will be applied to each item of the array (grouped, item) => { // 1st arg to reducer func is the accumulated value, returned after each loop // 2nd arg to reducer func is the item of the array for the current loop // If there's no prop named for this manager, makes one w/ empty array as value grouped[item.Manager] = grouped[item.Manager] || []; // Makes a two-item array of name and performance and pushes it to prop array grouped[item.Manager].push([item.name, item.Performance]); // The accumulated object has been updated, is ready to be used in next loop return grouped; }, // 2nd arg to `reduce` (an empty obj) to be used as `grouped` during first loop {} ); return obj; } // We'll pass the object into this function to get our desired format function formatFinalArray(obj){ const output = []; for(let key in obj){ output.push({ Manager: key, data: obj[key] }); } return output; } // Just provides our original array function getOriginalArray(){ return [ { "name": "Sean", "Manager": "Joe", "Performance": 5 }, { "name": "John", "Manager": "Joe", "Performance": 9 }, { "name": "Paul", "Manager": "Joe", "Performance": 0 }, { "name": "Derek", "Manager": "Greg", "Performance": 10 }, { "name": "Lisa", "Manager": "Greg", "Performance": 10 }, { "name": "Julia", "Manager": "Donna", "Performance": 7 } ]; }

暫無
暫無

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

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