我有一个正在解析并传递的对象。
看起来像这样:
var inputDescriptions = {
customText: {
message: "this is a message",
note: "this is a note"
},
tool: "wrench",
garage: "two-door",
"garage-color": "white",
message: "message",
"message-color": "white",
note: "note"
};
在解析结束时,我希望它是一个项目和描述的数组,如下所示:
这称为“inputDescriptions”
[{
item: "tool",
description: "wrench"
}, {
item: "garage",
description: "two-door"
}, {
item: "garage-color",
description: "white"
}, {
item: "noteText",
description: "this is a note"
}, {
item: "messageText",
description: "this is a message"
}, {
item: "message",
description: "message"
}, {
item: "note",
description: "note"
}]
我真的被一个具有两个属性的对象所困扰。
这是我拥有的功能:
const parseSelections = (inputDescriptions) => {
return Object.keys(inputDescriptions).map((choiceId) => {
const optionId = inputDescriptions[choiceId];
const userSelectionInput = {
choiceId,
optionId,
};
return userSelectionInput;
});
};
const selections = parseSelections(inputDescriptions);
已经接近但还没有完全实现:
[
{item: "tool", description: "wrench"}
{item: "garage", description: "two-door"}
{item: "garage-color", description: "white"}
{item: "customText", description: {message: "this is a message", note: "this is a note"}
{item: "message", description: "message"}
{item: "note", description: "note"}
]
我尝试使用 Object.assign 取出 customText 对象并重新分配,但我仍然无法让它工作。也许我需要创建一个新函数来再次解析?我觉得我已经很接近了,但那个物体却让我远离了。有谁有更好的想法来做到这一点的干净方法吗?
最佳答案
您需要从对象中删除 customText
属性并单独处理它。
let inputDescriptions = {
customText: {
message: "this is a message",
note: "this is a note"
},
tool: "wrench",
garage: "two-door",
"garage-color": "white",
message: "message",
"message-color": "white",
note: "note"
};
const parseSelections = (inputDescriptions) => {
inputDescriptions = Object.assign({}, inputDescriptions); // clone object
let customText = inputDescriptions.customText;
delete inputDescriptions.customText;
return Object.keys(inputDescriptions).map((choiceId) => {
const optionId = inputDescriptions[choiceId];
const userSelectionInput = {
choiceId,
optionId,
};
return userSelectionInput;
}).concat(
Object.entries(customText).map(([key, val]) => ({
choiceId: `${key}Text`,
optionId: val
}))
);
};
const selections = parseSelections(inputDescriptions);
console.log(selections);
关于javascript - 提取具有多个值的对象并使用 Javascript 传递它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57861528/