我有一个 JSON(由 giftpeg 生成),并且有一些对我来说无用的节点,例如“format:”moodle”(参见代码):
[
{
"type": "MC",
"title": null,
"stem":
{
"format":"moodle",
"text": "What is the main cause of the seasons on the earth?"
},
"hasEmbeddedAnswers": false,
"globalFeedback": null,
"choices":
[ {
"isCorrect": false,
"weight": null,
"text":
{
"format": "moodle",
"text": "the earth's elliptical (slightly oval) orbit around the sun" }, "feedback": null
},
{
"isCorrect": true,
"weight": null,
"text":
{ "format": "moodle",
"text": "the tilt of earth's axis with respect to the sun"
},
"feedback": null
},
{
"isCorrect": false,
"weight": null,
"text":
{
"format": "moodle",
"text": "the northern hemisphere has twice the land mass than the southern hemisphere"
},
"feedback": null
}
]
}
]
到目前为止,我可以删除“格式”节点(我认为我做对了),但有一些冗余,例如:
"text":{
"text": "foo"
}
目标是将其(以非破坏性的方式)转变为:
"text": "foo"
这是我的代码(尽我所能):
formatedQuestions(jsonItem) {
return jsonItem.map(question => {
question.choices.map(choice => {
delete choice.text.format;
choice = Object.assign(choice, choice.text);
delete choice.text.text;
return choice;
});
delete question.stem.format;
return question;
});
我可以移动它,但它会改变原始的 JSON。所以每次我调用它时它都会改变。这是一个问题。
这会将值“向上”移动,但它改变了原始值
choice = Object.assign(choice, choice.text);
如果您除了解决方案之外还有任何建议以使其更加实用和高效,我们将不胜感激。
最佳答案
const formatObj = obj => obj.format === "moodle" ? obj.text : Object.entries(obj).reduce((res, [key, value]) => ({ ...res, [key]: format(value) }), {});
const formatArray = array => array.map(format);
const format = it => (
Array.isArray(it) && formatArray(it) ||
typeof it === "object" && formatObj(it) ||
it
);
这是功能性的,是否“高效”甚至“可读”是另一回事。
我通常会怎么做:
function format(it) {
if(Array.isArray(it))
return it.map(format);
if(typeof it === "object") {
if(it.format === "moodle")
return it.text;
const result = {};
for(const [key, value] of Object.entries(it))
result[key] = format(value);
return result;
}
return it;
}
<小时/>
如果您不需要通用解决方案,这里是适合您的用例的特定解决方案:
formatedQuestions(jsonItem) {
return jsonItem.map(question => ({
....question,
stem: question.stem.text,
choices: question.choices.map(choice => ({
...choice,
text: choice.text.text || choice.text,
})),
}));
}
关于javascript - 我试图在纯函数中将值移动到父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641313/