亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過在 javascript 中保留數據(將值推送到數組中)來減少相同鍵值的對象數組?

通過在 javascript 中保留數據(將值推送到數組中)來減少相同鍵值的對象數組?

小唯快跑啊 2023-03-03 15:17:13
我有以下格式的數據,基本上是一個對象數組,我嘗試了幾種方法,我怎樣才能更有效地做到這一點?const overdue =  [        {            "user.employeeId": "10001440",            "objectives": [                "Understand the financial indexes."            ]        },        {            "user.employeeId": "10000303",            "objectives": [                "Document preparation & writing skills"            ]        },        {            "user.employeeId": "10002168",            "objectives": [                "Chia ratio setting for Fuze Tea products L11"            ]        },        {            "user.employeeId": "10002168",            "objectives": [                "Brix parameter differences between Processing and Production of Fuze Tea Lemon-Lemongrass standardization"            ]        },        {            "user.employeeId": "10002168",            "objectives": [                "Paramix Line 9 setting parameter standardization"            ]        },    ]我如何使用 lodash 通過 JavaScript 將其轉換為以下內容?[        {            "user.employeeId": "10001440",            "objectives": [                "Understand the financial indexs."            ]        },        {            "user.employeeId": "10000303",            "objectives": [                "Document preparation & writing skills"            ]        },        {            "user.employeeId": "10002168",            "objectives": [                "Brix parameter differences between Processing and Production of Fuze Tea Lemon-Lemongrass standardization",                "Paramix Line 9 setting parameter standardization",                "Chia ratio setting for Fuze Tea products L11"            ]        }    ]我試過 Array.map!和正常的邏輯,我們如何使用 lodash reduce 或 arr.reduce 更有效地做到這一點?
查看完整描述

4 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

您可以使用Array.reduce來獲得所需的結果,使用數組作為累加器。

我們枚舉過期數組中的每個對象,如果它不存在于輸出數組中,我們將其添加,否則我們將對象目標添加到輸出中的相關元素。

const overdue =  [ { "user.employeeId": "10001440", "objectives": [ "Understand the financial indexes." ] }, { "user.employeeId": "10000303", "objectives": [ "Document preparation & writing skills" ] }, { "user.employeeId": "10002168", "objectives": [ "Chia ratio setting for Fuze Tea products L11" ] }, { "user.employeeId": "10002168", "objectives": [ "Brix parameter differences between Processing and Production of Fuze Tea Lemon-Lemongrass standardization" ] }, { "user.employeeId": "10002168", "objectives": [ "Paramix Line 9 setting parameter standardization" ] }, ]; 


let result = overdue.reduce((res, row) => {

    let el = res.find(el => el["user.employeeId"] === row["user.employeeId"]);

    // If we find the object in the output array simply update the objectives

    if (el) {

       el.objectives = [...el.objectives, ...row.objectives];

    } else {

    // If we _don't_ find the object, add to the output array.

      res.push({ ...row});

    }

    return res;

}, [])


console.log("Result:",result);


查看完整回答
反對 回復 2023-03-03
?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

使用array.reduce對象并將其傳遞給累加器。在回調函數中檢查累加器是否具有與 的值相同的鍵user.employeeId。如果不是,則創建鍵并將迭代中的當前對象添加為它的值。如果已經有一個鍵,那么只需更新目標數組。在檢索值時Object.valuewhich 將給出一個數組


const overdue = [{

    "user.employeeId": "10001440",

    "objectives": [

      "Understand the financial indexes."

    ]

  },

  {

    "user.employeeId": "10000303",

    "objectives": [

      "Document preparation & writing skills"

    ]

  },

  {

    "user.employeeId": "10002168",

    "objectives": [

      "Chia ratio setting for Fuze Tea products L11"

    ]

  },


  {

    "user.employeeId": "10002168",

    "objectives": [

      "Brix parameter differences between Processing and Production of Fuze Tea Lemon-Lemongrass standardization"

    ]

  },

  {

    "user.employeeId": "10002168",

    "objectives": [

      "Paramix Line 9 setting parameter standardization"

    ]

  },

];




let newData = overdue.reduce((acc, curr) => {

  if (!acc[curr['user.employeeId']]) {

    acc[curr['user.employeeId']] = curr;

  } else {

    curr.objectives.forEach((item) => {

      acc[curr['user.employeeId']]['objectives'].push(item)

    })

  }

  return acc;

}, {});



console.log(Object.values(newData))


查看完整回答
反對 回復 2023-03-03
?
largeQ

TA貢獻2039條經驗 獲得超8個贊

我不確定如何在 lodash 中執行此操作,但這是我僅使用 vanilla Javascript 執行此操作的方法:


const overdue = [{

    "user.employeeId": "10001440",

    "objectives": [

      "Understand the financial indexes."

    ]

  },

  {

    "user.employeeId": "10000303",

    "objectives": [

      "Document preparation & writing skills"

    ]

  },

  {

    "user.employeeId": "10002168",

    "objectives": [

      "Chia ratio setting for Fuze Tea products L11"

    ]

  },


  {

    "user.employeeId": "10002168",

    "objectives": [

      "Brix parameter differences between Processing and Production of Fuze Tea Lemon-Lemongrass standardization"

    ]

  },

  {

    "user.employeeId": "10002168",

    "objectives": [

      "Paramix Line 9 setting parameter standardization"

    ]

  },

];


const combined = {};


overdue.forEach(o => {

  const id = o["user.employeeId"];

  const obj = o["objectives"][0];

  

  if(!combined[id]) { combined[id] = [obj]; }

  else { combined[id].push(obj); }

  

});


const result = [];


Object.keys(combined).forEach(key => {

  result.push({"user.employeeId" : key, "objectives" : combined[key]});

});


console.log(result);


查看完整回答
反對 回復 2023-03-03
?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

如果你可以使用 lodash,那么你就可以超越 reduce 并使用更具體的東西來滿足你的需求。在這種情況下,您可以考慮使用該_.groupBy方法,該方法將創建一個由user.employeeId值作為鍵的對象,其中包含值作為每個對象的數組。然后,您可以將對象的(即:具有相同 employeeId 的對象數組)映射到每個數組合并的合并對象objectives。最后,您可以獲取分組對象的值以獲得結果:

const overdue = [{ "user.employeeId": "10001440", "objectives": [ "Understand the financial indexes." ] }, { "user.employeeId": "10000303", "objectives": [ "Document preparation & writing skills" ] }, { "user.employeeId": "10002168", "objectives": [ "Chia ratio setting for Fuze Tea products L11" ] }, { "user.employeeId": "10002168", "objectives": [ "Brix parameter differences between Processing and Production of Fuze Tea Lemon-Lemongrass standardization" ] }, { "user.employeeId": "10002168", "objectives": [ "Paramix Line 9 setting parameter standardization" ] }, ];


const group = _.flow(

  arr => _.groupBy(arr, "user.employeeId"),

  g => _.mapValues(g, arr => _.mergeWith(...arr, (objV, srcV) => {

    if (_.isArray(objV)) return objV.concat(srcV);

  })),

  _.values

);


console.log(group(overdue));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

或者您可以將 vanilla JS 與.reduce()a 一起使用Map,這使用了 JS 的更多現代功能(節點 14.0.0 均支持),例如可選鏈接 ?.空合并運算符 ??

const overdue = [{ "user.employeeId": "10001440", "objectives": [ "Understand the financial indexes." ] }, { "user.employeeId": "10000303", "objectives": [ "Document preparation & writing skills" ] }, { "user.employeeId": "10002168", "objectives": [ "Chia ratio setting for Fuze Tea products L11" ] }, { "user.employeeId": "10002168", "objectives": [ "Brix parameter differences between Processing and Production of Fuze Tea Lemon-Lemongrass standardization" ] }, { "user.employeeId": "10002168", "objectives": [ "Paramix Line 9 setting parameter standardization" ] }, ];


const group = (arr, key) => Array.from(arr.reduce((m, obj) =>

  m.set(

    obj[key], 

    {...obj, objectives: [...(m.get(obj[key])?.objectives ?? []), ...obj.objectives]}

  ), new Map).values()

);


console.log(group(overdue, "user.employeeId"));



查看完整回答
反對 回復 2023-03-03
  • 4 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號