gpt4 book ai didi

javascript - typescript 或 JavaScript 将嵌套的对象数组转换为键值对

转载 作者:行者123 更新时间:2023-12-04 09:36:36 28 4
gpt4 key购买 nike

下面的数组是输入和期望各自的 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()非常适合解决问题。

interface Output {
key: string;
value: string;
}

const result: Output[] = arr.map((item) => {
const output = {
key: item.id,
value: `${item.questions.map(elem => elem.question).join(', ')}: ${item.answer}`
};

return output;
});

console.log(result)

关于javascript - typescript 或 JavaScript 将嵌套的对象数组转换为键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62554333/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com