javascript - typescript 或 JavaScript 将嵌套的对象数组转换为键值对
问题描述
下面的数组是输入并期望各自的 O/P。如何使用 Typescript 将其实现为键值对
let arr = [
{id: "1",
questions: [
{question: "HTML Tutorial" },
{question: "HTML References" }
],
answer : "Hypertext Markup Language is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets and scripting languages such as JavaScript and VBScript."
},
{id: "2",
questions: [
{question: "HTML Element Reference" },
{question: "HTML Reference - Browser Support" }
],
answer : "An HTML element is a type of HTML document component, one of several types of HTML nodes. HTML document is composed of a tree of simple HTML nodes, such as text nodes, and HTML elements, which add semantics and formatting to parts of document. Each element can have HTML attributes specified."
}
];
// Expected Output using Typescript
Array [{ Key: "1", value: "HTML Tutorial, HTML References: Hypertext Markup Language is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets and scripting languages such as JavaScript and VBScript." },
{ Key: "2", value: "HTML Element Reference,HTML Reference - Browser Support : An HTML element is a type of HTML document component, one of several types of HTML nodes. HTML document is composed of a tree of simple HTML nodes, such as text nodes, and HTML elements, which add semantics and formatting to parts of document. Each element can have HTML attributes specified." }]
解决方案
使用map()
let arr = [{id:"1",questions:[{question:"HTML Tutorial"},{question:"HTML References"}],answer:"Hypertext Markup Language is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets and scripting languages such as JavaScript and VBScript."},{id:"2",questions:[{question:"HTML Element Reference"},{question:"HTML Reference - Browser Support"}],answer:"An HTML element is a type of HTML document component, one of several types of HTML nodes. HTML document is composed of a tree of simple HTML nodes, such as text nodes, and HTML elements, which add semantics and formatting to parts of document. Each element can have HTML attributes specified."}];
let res = arr.map(i => {
let q = i.questions.map(q => q.question).join(', ')
return { Key: i.id, value: q + ' : ' + i.answer }
});
console.log(res)
推荐阅读
- python - 石头剪刀布功能没有出现
- julia - 如何在 Julia 中将一些数据附加到文件中?
- nginx - 将 NGINX 配置语句从 `listen 80;` 更改为 `listen 80 http2;`
- c - C: 如何将 %20 转换为空格?
- java - maven war 文件如何在 meta-inf 文件夹的 maven 文件夹中有两个项目/pom.xml?
- macos - MACOS 上的 MACOSX M1 ARM64 Visual Studio 代码无法启动带有 C++ 应用程序的调试器
- python-3.x - 为什么排序功能在这两种情况下都有效?
- html - Livewire方法wire:单击按钮不起作用
- wpf - WPF 错误验证不显示 ErrorTemplate
- firebase - Flutter:Firebase Firestore 给出“所需参考处不存在对象”。删除时