简体   繁体   English

Typescript / Javascript:将对象数组转换为键,值对

[英]Typescript/Javascript: convert array of objects to key,value pair

in my application (React-typescript) I have some documents in the type of 在我的应用程序(React-typescript)中,我有一些类型的文档

interface IDocument {id: string;  questions: IQuestion[];}

interface IQuestion {number: string;  answer: string; }

so an array of documents will look like ie: 所以一系列文档看起来像是:

doscuments: IDocument[] = [
  {id: "a",
    questions: [
      { number: "1", answer: "answer1" },
        ... /* more number answer*/
    ]},
  {id: "b",
    questions: [
      { number: "1", answer: "answer1" },
        ... /* more number answer*/
    ]}
];

now I want to convert it to an alternative form of type 现在我想将其转换为另一种类型的形式

interface IAlternative {
  [key: string]: string;
}

to have key-value pairs of ie 具有ie的键值对

alterDocs: IAlternative = {a1:"answer1", a2:"answer2",...,b1:"answer1",...}

For that I have the code below but cannot construct a pair with doc.id+question.number as key and question.answer as the value 为此,我有下面的代码,但是不能构造一个以doc.id+question.number为键,而question.answer为值的对

documents.forEach(doc:IDocument=>{
 doc.questions.forEach(question=>{
    const pair= {} // I cannot construct this pair
    alterDocs={...alterDocs,...pair}
  })
})

You can use reduce 您可以使用减少

Here idea is 这里的主意是

  • Loop through arr , get id and questions from element 遍历arr ,从元素获取idquestions
  • No Loop on questions add key and value as per desired format 没有questions循环,可根据所需格式添加键和值

 let arr = [ {id: "a", questions: [ { number: "1", answer: "answer1" }, { number: "2", answer: "answer2" } ]}, {id: "b", questions: [ { number: "1", answer: "answer1" }, { number: "2", answer: "answer2" } ]} ]; let op = arr.reduce((op,inp)=>{ let key = inp.id let value = inp.questions value.forEach(e=>{ op[`${key}${e.number}`] = op[`key${e.number}`] || {} op[`${key}${e.number}`] = e.answer }) return op },{}) console.log(op) 

You can use the reduce function to get the data structure you want. 您可以使用reduce函数获取所需的数据结构。

const alterDocs = documents.reduce((total, doc: IDocument): IAlternative[] => {

  // loop through the questions and create an array of IAlternative objects
  const subDocs = doc.questions.reduce((aggregator, question: IQuestion): IAlternative[] => {

    // push the next question onto the IAlternative object
    aggregator.push({
      `${doc.id}${question.number}`: question.answer,
    });

    // return the IAlternative array
    return aggregator
  }, []);

  //  You will have an array of IAlternative documents.  Append this onto 
  //  the parent IAlternative array with concat
  total.concat(subDocs);
  return total;
}, []);

I found out that it was much simpler than I thought :) Thanks to answers but there was no need for complicated reducers 我发现它比我想象的要简单得多:)多亏了答案,但没有必要使用复杂的减速器

   alterDocs: IAlternative = {}

    documents.forEach(doc=>{
    const id=doc.id;
    doc.questions.forEach(q=>{
        const num=q.number;
        const ans=q.answer;
        alterDocs[`${id}${num}`]=ans;
      })
    })

 let documents = [ {id: "A", questions: [ { number: "1", answer: "answerA1" }, { number: "2", answer: "answerA2" }, { number: "3", answer: "answerA3" } ] }, {id: "B", questions: [ { number: "1", answer: "answerB1" }, { number: "2", answer: "answerB2" }, { number: "3", answer: "answerB3" } ] }, {id: "C", questions: [ { number: "1", answer: "answerC1" }, { number: "2", answer: "answerC2" }, { number: "3", answer: "answerC3" } ] } ]; let altDocs = {}; documents.forEach(doc => { const id = doc.id; doc.questions.forEach(q => { const num = q.number; altDocs[`${id}${num}`] = q.answer; }); }); console.log(altDocs); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM