首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >javascript从新对象中的键值对的两级数组中提取id

javascript从新对象中的键值对的两级数组中提取id
EN

Stack Overflow用户
提问于 2018-06-28 04:58:39
回答 3查看 28关注 0票数 0

我得到了一个有效负载,我需要从有效负载中的两个单独的级别拉取id,并将其作为键值对的单个对象返回。我试图做一些组合,或者ForEach()reduce(),但是我似乎找不到正确的方法。下面是数据的样子。

{
 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" }]
  }]
}

我想要得到的结果

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-06-28 05:16:35

使用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);

票数 1
EN

Stack Overflow用户

发布于 2018-06-28 05:09:15

您可以使用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)

票数 0
EN

Stack Overflow用户

发布于 2018-06-28 05:55:42

这是简单的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));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51071302

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档