简体   繁体   English

javascript从新对象中的键值对的两个级别的数组中提取ID

[英]javascript extract id's from two levels of arrays for key value pairs in new object

I'm getting a payload back that I need to pull id's from two separate levels within the payload and return it as a single object of key value pairs. 我收到一个有效载荷,需要从有效载荷内的两个单独级别中提取ID,并将其作为键值对的单个对象返回。 I was attempting to do some sort of combination or ForEach() and reduce() but I couldn't seem to find the right way of doing it. 我试图进行某种组合或ForEach()reduce()但似乎找不到正确的方法。 Here is a what the data looks like. 这是数据的样子。

{
 orderId:999,
 menuId: 123456,
  questions:[{
    questionId: 123,
    depth: 1,
        answers: [
            { answerId: 999, text: "foo1" },
            { answerId: 888, text: "foo2" }]
  },
  {
    questionId: 654,
    depth: 1,
    answers: [{ answerId: 777, text: "bar" }]
  }]
}

What I'm attempting to have as the result 结果是我想要的

{"q_123": ["999", "888"], "q_654": "777"}

The following approach with reduce will do the job: 以下带有reduce方法将完成这项工作:

 const data = { orderId: 999, menuId: 123456, questions: [{ questionId: 123, depth: 1, answers: [{ answerId: 999, text: "foo1" }, { answerId: 888, text: "foo2" } ] }, { questionId: 654, depth: 1, answers: [{ answerId: 777, text: "bar" }] } ]}; const result = data.questions.reduce((all, { questionId: id, answers }) => { all[`q_${id}`] = answers.map(a => a.answerId); return all; }, {}); console.log(result); 

you can use reduce to achieve this : 您可以使用reduce实现此目的:

 const data = { orderId: 999, menuId: 123456, questions: [ { questionId: 123, depth: 1, answers: [ { answerId: 999, text: "foo1"}, { answerId: 888, text: "foo2"} ] }, { questionId: 654, depth: 1, answers: [ { answerId: 777, text: "bar" }] } ] } const result = data.questions.reduce((acc, {questionId, answers}) => { return Object.assign({ [`q_${questionId}`]: answers.map( ({answerId}) => answerId ) }, acc) }, {}); console.log(result) 

This is with simple JSON parsing . 这是简单的JSON parsing

 var input = { orderId:999, menuId: 123456, questions:[{ questionId: 123, depth: 1, answers: [ { answerId: 999, text: "foo1" }, { answerId: 888, text: "foo2" }] }, { questionId: 654, depth: 1, answers: [{ answerId: 777, text: "bar" }] }] }; var length = input.questions.length; var questionsobj = input.questions; var resultJsonData = {}; for(var i=0; i<length; i++) { var question_id = questionsobj[i].questionId; var answersobj = questionsobj[i].answers; var len = answersobj.length; var arrayObject = []; for(var k=0; k<len; k++) { arrayObject[k] = answersobj[k].answerId; } resultJsonData["q_" + question_id] = arrayObject; } console.log(JSON.stringify(resultJsonData)); 

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

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