【问题标题】:Filter one array by type, depending other按类型过滤一个数组,取决于其他数组
【发布时间】:2021-12-31 01:56:30
【问题描述】:

我需要根据 Header_Tasks.type 从 body_Task 创建两个结果

Header_Tasks

[
  {"_id":"AAA54" "title":"task 1" "type":1},
  {"_id":"bbb45" "title":"task 2" "type":2},
  {"_id":"ccc56" "title":"task 3" "type":1},
  {"_id":"xxx98" "title":"task 4" "type":2},
]

我是根据 Header_Tasks 创建的, 它的名字是body_taks,我将数据(标题,正文)保存在我的数据库中,因为它在我的项目中还有其他功能

body_taks

{
  "AAA54":10,
  "AAA54|max":10,
  "bbb45":07,
  "bbb45|max":20,
  "ccc56":05,
  "ccc56|max":30,
  "xxx98":03,
  "xxx98|max":15,
}

我希望,两个结果取决于 Header_Tasks.type

类型 1

{
  "AAA54":10,
  "AAA54|max":10,
  "ccc56":05,
  "ccc56|max":30,
}

类型 2

{
  "bbb45":07,
  "bbb45|max":20,
  "xxx98":03,
  "xxx98|max":15,
}

【问题讨论】:

    标签: javascript arrays vue.js


    【解决方案1】:

    这可以通过一个相当标准的“分组依据”来完成,首先创建一个Map 来查找类型,然后在结果对象中按类型分组。

    const headerTasks = [{ _id: "AAA54", title: "task 1", type: 1 }, { _id: "bbb45", title: "task 2", type: 2 }, { _id: "ccc56", title: "task 3", type: 1 }, { _id: "xxx98", title: "task 4", type: 2 },];
    const bodyTasks = { AAA54: 10, "AAA54|max": 10, bbb45: "07", "bbb45|max": 20, ccc56: "05", "ccc56|max": 30, xxx98: "03", "xxx98|max": 15, };
    
    const typeMap = new Map(headerTasks.map((t) => [t._id, t.type]));
    
    const result = {};
    
    for (const key in bodyTasks) {
        const id = key.includes("|") ? key.slice(0, key.indexOf("|")) : key;
        const t = typeMap.get(id);
        if (t !== undefined) {
            result[`type${t}`] ??= {};
            result[`type${t}`][key] = bodyTasks[key];
        }
    }
    
    console.log(result);

    注意:我已将以 0 开头的数字转换为字符串,因为 [八进制文字] 在严格模式下是不允许的,我不确定您是否打算将它们作为八进制。 p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多