我得到了一个有效负载,我需要从有效负载中的两个单独的级别拉取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"}
发布于 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);
发布于 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)
发布于 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));
https://stackoverflow.com/questions/51071302
复制相似问题