我试图将以下“详细信息”对象中的值分配给“ formFields”数组中的每个“模型”。
这是详细信息对象
const details = {
criteriaName: "hello",
criteriaType: "type a",
description: "world"
}
这是formFields数组
从上面的细节对象中,我试图将每个键中的每个值分配给formFields数组中的每个模型
const formFields = [
{
"title": "Title 1",
"columns": 2,
"fields": {
"criteriaName": {
"type": "text",
"label": "Criteria Name",
"id": 'criteriaName',
"model": "",
"required": true,
"show": true,
"rules": [
v => !!v || 'Criteria Name is required',
]
},
"criteriaType": {
"type": "select",
"label": "Criteria type",
"id": "criteriaType",
"options": ['Dependent', 'Independent', 'Static'],
"model": "",
"required": true,
"rules": [
v => !!v || 'Criteria Type is required',
],
"show": true,
},
}
},
{
'title': "Title 2",
"columns": 1,
"fields": {
"description": {
"type": "description_notes",
"label": "Description",
"id": "description",
"required": false,
"model": '',
"show": true,
}
}
}
]
我该如何实现?
谢谢。
答案 0 :(得分:1)
formFields.forEach((form) => {
if (form.fields.criteriaName) form.fields.criteriaName.model = details.criteriaName;
if (form.fields.criteriaType) form.fields.criteriaType.model = details.criteriaType;
if (form.fields.description) form.fields.description.model = details.description;
})
这将对原始数组进行更改。 您可以阅读有关forEach here
的更多信息。如果要创建具有更改的新数组,可以使用:
let newFormFields = formFields.map((form) => {
if (form.fields.criteriaName) form.fields.criteriaName.model = details.criteriaName;
if (form.fields.criteriaType) form.fields.criteriaType.model = details.criteriaType;
if (form.fields.description) form.fields.description.model = details.description;
return form;
});
您可以了解有关地图here
的更多信息答案 1 :(得分:0)
欢迎堆栈溢出。以下代码可能会满足您的要求。要解释所有详细信息需要花费很多时间,但是您可以在评论中提问并阅读一些documentation
const details = {
criteriaName: 'hello',
criteriaType: 'type a',
description: 'world',
};
const formFields = [
{
title: 'Title 1',
fields: {
criteriaName: {
id: 'criteriaName',
model: '',
},
criteriaType: {
id: 'criteriaType',
model: '',
},
},
},
{
title: 'Title 2',
fields: {
description: {
id: 'description',
model: '',
},
nonExisting: {
id: 'nonExisting',
model: 'this will not be replaced',
},
},
},
];
const result = formFields.map((formField) => ({
...formField,
fields: Object.entries(formField.fields).reduce(
(fields, [key, value]) =>
details[key]
? {
...fields,
[key]: { ...value, model: details[key] },
}
: fields,
formField.fields,
),
}));
console.log(result);