更改对象结构Javascript



我有一个数组,我想覆盖对象属性

这是的主要数据

const Data = {
"id": "1",
"name": "USA",
"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id: 3, name: "3 qst" }],
"children": [
{ "id": "1" , "name": "DC" ,"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id:2, name: "3 qst" }]},
{ "id": "2" , "name": "Florida" ,"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id: 3, name: "3 qst" }]}
]
}

我想在每个问题中更改,而不是更改名称我想把questionName像这个一样

{ id: 1, questionName: "1 qst" }

我能够通过这个代码在第一个对象问题中更改它

let dataFiltred = Data[0]?.questions?.map((item) => {
return {
questionName: item.name,
id: item.id,

}
})

但我正在努力改变它在儿童问题

function mapQuestionObject({ name, id }) {
return { id, questionName: name };
}
const mapped = {
...Data,
questions: Data.questions.map(mapQuestionObject),
children: Data.children.map(child => ({
...child,
questions: child.questions.map(mapQuestionObject),
}),
};

将每个questions数组映射到一个新数组,并更改映射值中的name属性。

const data = {
"id": "1",
"name": "USA",
"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id: 3, name: "3 qst" }],
"children": [
{ "id": "1" , "name": "DC" ,"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id:2, name: "3 qst" }]},
{ "id": "2" , "name": "Florida" ,"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id: 3, name: "3 qst" }]}
]
};
const newData = {
...data,
questions: data.questions.map(({ name: questionName, ...rest }) => ({
...rest,
questionName,
})),
children: data.children.map(child => ({
...child,
questions: child.questions.map(({ name: questionName, ...rest }) => ({
...rest,
questionName,
}))
})),
};
console.log(newData);

由于问题映射是相同的回调,您可以将其考虑在内,使您的代码更加DRY

const data = {
"id": "1",
"name": "USA",
"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id: 3, name: "3 qst" }],
"children": [
{ "id": "1" , "name": "DC" ,"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id:2, name: "3 qst" }]},
{ "id": "2" , "name": "Florida" ,"questions": [{ id: 1, name: "1 qst" }, { id: 2, name: "2 qst" }, { id: 3, name: "3 qst" }]}
]
};
const mapQuestions = arr => arr.map(({ name: questionName, ...rest }) => ({
...rest,
questionName,
}));
const newData = {
...data,
questions: mapQuestions(data.questions),
children: data.children.map(child => ({
...child,
questions: mapQuestions(child.questions),
})),
};
console.log(newData);

最新更新