按名称分组数组数据

时间:2019-01-28 09:27:13

标签: javascript arrays vanilla-typescript pure-js

我正在尝试开发一个具有“运输”专业知识的数组,其中包含每个部门以及分配给他们的文本。

这就是我所拥有的:


    - Healthcare
    -- Data-driven insights to improve healthcare
    -- Novel data mining and visualisation
    -- Human-centred augmented and virtual realities

    - Energy
    -- Urban Analytics
    -- Understanding patterns of consumer behaviour
    -- Optimising energy systems

这就是我想要做的:


    - expertise (e.g Transport)

    -- sector (e.g Data)
    --- text (e.g Urban Analytics)
    --- text (e.g Understanding patterns of consumer behaviour)
    --- text (e.g Human-centred augmented and virtual realities)

    -- sector (e.g Engineering)
    --- text (e.g Optimising energy systems)
    --- text (e.g High speed rail and system integration innovation)
    --- text (e.g Human-centred robotic and autonomous systems)
    --- text (e.g Surface engineering across the length scales)

    -- sector (e.g Environment)
    --- text (e.g Europe’s leading city simulation capability)

    - expertise
    -- sector
    --- text

如果有人能提供帮助,这是我目前正在使用的代码,我将非常感激。

var items = [{
    "item": {
      "id": 0,
      "sector": 'Data',
      "expertise": ["Healthcare"],
      "text": "Data-driven insights to improve healthcare"
    }
  },
  {
    "item": {
      "id": 1,
      "sector": 'Data',
      "expertise": ["Energy", "Transport", "Cities"],
      "text": "Urban Analytics"
    }
  },
  {
    "item": {
      "id": 2,
      "sector": 'Data',
      "expertise": ["Energy", "Transport", "Consumer"],
      "text": "Understanding patterns of consumer behaviour"
    }
  },
  {
    "item": {
      "id": 3,
      "sector": 'Data',
      "expertise": ["Healthcare", "Consumer"],
      "text": "Novel data mining and visualisation"
    }
  },
  {
    "item": {
      "id": 4,
      "sector": 'Data',
      "expertise": ["Healthcare", "Transport", "Consumer"],
      "text": "Human-centred augmented and virtual realities"
    }
  },
  {
    "item": {
      "id": 5,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Medical technology innovation, translation and convergence"
    }
  },
  {
    "item": {
      "id": 6,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Understanding cardio metabolic disease"
    }
  },
  {
    "item": {
      "id": 7,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Improving early cancer diagnosis and treatment"
    }
  },
  {
    "item": {
      "id": 8,
      "sector": 'Healthcare',
      "expertise": ["Healthcare", "Pharmaceuticals"],
      "text": "Understanding life in molecular detail"
    }
  },
  {
    "item": {
      "id": 9,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Evidencing treatment through clinical trials"
    }
  },
  {
    "item": {
      "id": 10,
      "sector": 'Engineering',
      "expertise": ["Energy", "Transport"],
      "text": "Optimising energy systems"
    }
  },
  {
    "item": {
      "id": 11,
      "sector": 'Engineering',
      "expertise": ["Energy"],
      "text": "Enhancing petroleum recovery"
    }
  },
  {
    "item": {
      "id": 12,
      "sector": 'Engineering',
      "expertise": ["Transport"],
      "text": "High speed rail and system integration innovation"
    }
  },
  {
    "item": {
      "id": 13,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Electronics"],
      "text": "Terahertz frequency electronic and photonic devices"
    }
  },
  {
    "item": {
      "id": 14,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Transport", "Manufacturing"],
      "text": "Human-centred robotic and autonomous systems"
    }
  },
  {
    "item": {
      "id": 15,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Energy", "Transport", "Manufacturing"],
      "text": "Surface engineering across the length scales"
    }
  },
  {
    "item": {
      "id": 16,
      "sector": 'Engineering',
      "expertise": ["Pharmaceuticals", "Manufacturing"],
      "text": "Chemical and process engineering from molecule to product"
    }
  },
  {
    "item": {
      "id": 17,
      "sector": 'Engineering',
      "expertise": ["Pharmaceuticals"],
      "text": "Bionanotechnology for disease diagnosis, treatment and prevention"
    }
  },
  {
    "item": {
      "id": 18,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Pharmaceuticals", "Electronics", "Manufacturing"],
      "text": "Engineering materials at the atomic level"
    }
  },
  {
    "item": {
      "id": 19,
      "sector": 'Environment',
      "expertise": ["Healthcare", "Environment & Food"],
      "text": "Addressing global challenges in food security"
    }
  },
  {
    "item": {
      "id": 20,
      "sector": 'Environment',
      "expertise": ["Healthcare", "Environment & Food"],
      "text": "Interdisciplinary approaches to tackling major water issues"
    }
  },
  {
    "item": {
      "id": 21,
      "sector": 'Environment',
      "expertise": ["Cities"],
      "text": "Designing cities of the future"
    }
  },
  {
    "item": {
      "id": 22,
      "sector": 'Environment',
      "expertise": ["Transport", "Cities"],
      "text": "Europe’s leading city simulation capability"
    }
  },
  {
    "item": {
      "id": 23,
      "sector": 'Environment',
      "expertise": ["Environment & Food"],
      "text": "Robust and timely climate solutions"
    }
  }
];

let expertise;
let res = items.reduce((acc, {
  item: {
    expertise,
    text
  }
}) => {
  expertise.forEach(x => acc[x] = [...(acc[x] || []), text]);
  return acc;
}, {});


Object.entries(res).forEach(([k, v]) => {
  console.log(k + "\n->" + v.join("\n->"));
});

2 个答案:

答案 0 :(得分:1)

您还需要一个级别的扇区:

var items = [{"item": {"id": 0,"sector": 'Data',"expertise": ["Healthcare"],"text": "Data-driven insights to improve healthcare"}},{"item": {"id": 1,"sector": 'Data',"expertise": ["Energy", "Transport", "Cities"],"text": "Urban Analytics"}},{"item": {"id": 2,"sector": 'Data',"expertise": ["Energy", "Transport", "Consumer"],"text": "Understanding patterns of consumer behaviour"}},{"item": {"id": 3,"sector": 'Data',"expertise": ["Healthcare", "Consumer"],"text": "Novel data mining and visualisation"}},{"item": {"id": 4,"sector": 'Data',"expertise": ["Healthcare", "Transport", "Consumer"],"text": "Human-centred augmented and virtual realities"}},{"item": {"id": 5,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Medical technology innovation, translation and convergence"}},{"item": {"id": 6,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Understanding cardio metabolic disease"}},{"item": {"id": 7,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Improving early cancer diagnosis and treatment"}},{"item": {"id": 8,"sector": 'Healthcare',"expertise": ["Healthcare", "Pharmaceuticals"],"text": "Understanding life in molecular detail"}},{"item": {"id": 9,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Evidencing treatment through clinical trials"}},{"item": {"id": 10,"sector": 'Engineering',"expertise": ["Energy", "Transport"],"text": "Optimising energy systems"}},{"item": {"id": 11,"sector": 'Engineering',"expertise": ["Energy"],"text": "Enhancing petroleum recovery"}},{"item": {"id": 12,"sector": 'Engineering',"expertise": ["Transport"],"text": "High speed rail and system integration innovation"}},{"item": {"id": 13,"sector": 'Engineering',"expertise": ["Healthcare", "Electronics"],"text": "Terahertz frequency electronic and photonic devices"}},{"item": {"id": 14,"sector": 'Engineering',"expertise": ["Healthcare", "Transport", "Manufacturing"],"text": "Human-centred robotic and autonomous systems"}},{"item": {"id": 15,"sector": 'Engineering',"expertise": ["Healthcare", "Energy", "Transport", "Manufacturing"],"text": "Surface engineering across the length scales"}},{"item": {"id": 16,"sector": 'Engineering',"expertise": ["Pharmaceuticals", "Manufacturing"],"text": "Chemical and process engineering from molecule to product"}},{"item": {"id": 17,"sector": 'Engineering',"expertise": ["Pharmaceuticals"],"text": "Bionanotechnology for disease diagnosis, treatment and prevention"}},{"item": {"id": 18,"sector": 'Engineering',"expertise": ["Healthcare", "Pharmaceuticals", "Electronics", "Manufacturing"],"text": "Engineering materials at the atomic level"}},{"item": {"id": 19,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Addressing global challenges in food security"}},{"item": {"id": 20,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Interdisciplinary approaches to tackling major water issues"}},{"item": {"id": 21,"sector": 'Environment',"expertise": ["Cities"],"text": "Designing cities of the future"}},{"item": {"id": 22,"sector": 'Environment',"expertise": ["Transport", "Cities"],"text": "Europe’s leading city simulation capability"}},{"item": {"id": 23,"sector": 'Environment',"expertise": ["Environment & Food"],"text": "Robust and timely climate solutions"}}];

const res = items.reduce((acc, {item: {sector, expertise, text}}) => {
    expertise.forEach(exp => {
        acc[exp] = acc[exp] || {};
        acc[exp][sector] = [...(acc[exp][sector] || []), text];
    });
    return acc;
}, {});

Object.entries(res).forEach(([exp, sectors]) => {
    console.log("- " + exp);
    Object.entries(sectors).forEach(([sector, texts]) => {
        console.log("-- " + sector + "\n--- " + texts.join("\n--- "));
    });
});

说明

reduce操作中,sector也从对象中获取。就像在原始版本中一样,专业知识也在不断地迭代,但是现在acc对象变成了两个级别的对象,而不仅仅是一个级别。一级属性是专业知识(exp)。如果此类属性尚不存在,它将获得一个空对象作为值:

        acc[exp] = acc[exp] || {};

接下来的行非常像您已经拥有的行:下一个属性级别由扇区组成,并且对于每个扇区,将维护文本数组。

代码的第二部分采用与您已经拥有的原理相同的原理,但又增加了一层。首先,对专业知识属性进行迭代。它们具有对象作为值,每个对象都有扇区属性。然后,内部循环又非常像您所拥有的:对于每个扇区,将显示扇区和相关的文本值。

答案 1 :(得分:1)

您可以尝试以下通用方法:

想法

  • 创建一个打印以下内容的函数( say A ):
    • 子弹,在此解决方案-
    • 正在使用的密钥
    • 此键的值以特定格式显示。
  • 还创建一个函数( say B ),该函数解析并返回格式化的字符串作为值。
    • 对于数组,它将使用Array.join
    • 对于非空对象,它将使用您在上面创建的相同功能( A )。
    • 对于非空文字值,它将返回value.toString()
    • 对于空值,它将返回一个空白值。

  • 函数AB均表示较低/较低级别。因此,您将必须向现有的项目符号字符串中添加-或项目符号值。
  • 由于它是嵌套结构,因此您将必须清理字符串(使用\n 删除多余的string.trim() ),以免得到多行新行。
  • li>
  • 使用这些互连功能将以必要的格式打印,而与深度无关。

function isEmpty(value) {
  return value === null || value === undefined
}

function getValueString(v, preString) {
  preString = `\n${preString.trim()}-`;
  return Array.isArray(v) && (preString + v.join(preString)) ||
    typeof v === 'object' && nestedLevelToString(v, preString) ||
    isEmpty(v) && v.toString() ||
    '';
}

function nestedLevelToString(data, preString) {
  preString = preString || '-';
  let output = ''
  for (const key in data) {
    output += `${preString}${key}${getValueString(data[key], preString)}`;
  }
  return output;
}

var items = [{"item": {"id": 0,"sector": 'Data',"expertise": ["Healthcare"],"text": "Data-driven insights to improve healthcare"}},{"item": {"id": 1,"sector": 'Data',"expertise": ["Energy", "Transport", "Cities"],"text": "Urban Analytics"}},{"item": {"id": 2,"sector": 'Data',"expertise": ["Energy", "Transport", "Consumer"],"text": "Understanding patterns of consumer behaviour"}},{"item": {"id": 3,"sector": 'Data',"expertise": ["Healthcare", "Consumer"],"text": "Novel data mining and visualisation"}},{"item": {"id": 4,"sector": 'Data',"expertise": ["Healthcare", "Transport", "Consumer"],"text": "Human-centred augmented and virtual realities"}},{"item": {"id": 5,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Medical technology innovation, translation and convergence"}},{"item": {"id": 6,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Understanding cardio metabolic disease"}},{"item": {"id": 7,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Improving early cancer diagnosis and treatment"}},{"item": {"id": 8,"sector": 'Healthcare',"expertise": ["Healthcare", "Pharmaceuticals"],"text": "Understanding life in molecular detail"}},{"item": {"id": 9,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Evidencing treatment through clinical trials"}},{"item": {"id": 10,"sector": 'Engineering',"expertise": ["Energy", "Transport"],"text": "Optimising energy systems"}},{"item": {"id": 11,"sector": 'Engineering',"expertise": ["Energy"],"text": "Enhancing petroleum recovery"}},{"item": {"id": 12,"sector": 'Engineering',"expertise": ["Transport"],"text": "High speed rail and system integration innovation"}},{"item": {"id": 13,"sector": 'Engineering',"expertise": ["Healthcare", "Electronics"],"text": "Terahertz frequency electronic and photonic devices"}},{"item": {"id": 14,"sector": 'Engineering',"expertise": ["Healthcare", "Transport", "Manufacturing"],"text": "Human-centred robotic and autonomous systems"}},{"item": {"id": 15,"sector": 'Engineering',"expertise": ["Healthcare", "Energy", "Transport", "Manufacturing"],"text": "Surface engineering across the length scales"}},{"item": {"id": 16,"sector": 'Engineering',"expertise": ["Pharmaceuticals", "Manufacturing"],"text": "Chemical and process engineering from molecule to product"}},{"item": {"id": 17,"sector": 'Engineering',"expertise": ["Pharmaceuticals"],"text": "Bionanotechnology for disease diagnosis, treatment and prevention"}},{"item": {"id": 18,"sector": 'Engineering',"expertise": ["Healthcare", "Pharmaceuticals", "Electronics", "Manufacturing"],"text": "Engineering materials at the atomic level"}},{"item": {"id": 19,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Addressing global challenges in food security"}},{"item": {"id": 20,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Interdisciplinary approaches to tackling major water issues"}},{"item": {"id": 21,"sector": 'Environment',"expertise": ["Cities"],"text": "Designing cities of the future"}},{"item": {"id": 22,"sector": 'Environment',"expertise": ["Transport", "Cities"],"text": "Europe’s leading city simulation capability"}},{"item": {"id": 23,"sector": 'Environment',"expertise": ["Environment & Food"],"text": "Robust and timely climate solutions"}}];


let expertise;
const res = {};
res['sector'] = items.reduce((acc, {
  item: {
    expertise,
    text
  }
}) => {
  expertise.forEach(x => acc[x] = [...(acc[x] || []), text]);
  return acc;
}, {});

console.log(nestedLevelToString(res));