通过在 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"

            ]

        },

    ]

我如何使用 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 更有效地做到这一点?


小唯快跑啊
浏览 131回答 4
4回答

千万里不及你

您可以使用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);

慕盖茨4494581

使用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))

largeQ

我不确定如何在 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);

慕姐8265434

如果你可以使用 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(&nbsp; arr => _.groupBy(arr, "user.employeeId"),&nbsp; g => _.mapValues(g, arr => _.mergeWith(...arr, (objV, srcV) => {&nbsp; &nbsp; if (_.isArray(objV)) return objV.concat(srcV);&nbsp; })),&nbsp; _.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 均支持),例如可选链接&nbsp;?.和空合并运算符&nbsp;??: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) =>&nbsp; m.set(&nbsp; &nbsp; obj[key],&nbsp;&nbsp; &nbsp; {...obj, objectives: [...(m.get(obj[key])?.objectives ?? []), ...obj.objectives]}&nbsp; ), new Map).values());console.log(group(overdue, "user.employeeId"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript