这两个参数都是对象列表。它们都包含属性Name。我想预测一些属性名称相同的属性。以下给出了正确的结果。但是,有人可以帮我重构一次遍历吗?
export function fieldProjections(docTypeFields, recordFields) {
const recordsByName = recordFields.reduce(function (rec, field) {
rec[field.Name] = field;
return rec;
}, {});
const fields = docTypeFields.map(dt => {
return {
'Name': dt.Name,
'RawValue': recordsByName[dt.Name].RawValue,
'Type': dt.DataType,
'Value': recordsByName[dt.Name].Value,
'Id': dt.DocumentTypeFieldID
};
});
return fields;
}
答案 0 :(得分:0)
let docTypeFields = [{Name: 'doc1', RawValue: '8', Type: 'large', Value: '3.50', Id: '1'},{Name: 'doc2', RawValue: '11', Type: 'medium', Value: '4.50', Id: '2'},{Name: 'doc3', RawValue: '81', Type: 'largish', Value: '3.60', Id: '3'},{Name: 'doc4', RawValue: '22', Type: 'small', Value: '2.50', Id: '4'}],
recordFields = [{Name: 'doc1', Field: 'field1'},{Name: 'doc2', Field: 'field2'},{Name: 'doc3', Field: 'field3'},{Name: 'doc4', Field: 'field4'}];
docTypeFields.forEach(doc => {
let siblingRecord = recordFields.find(record => record.Name === doc.Name);
if (siblingRecord) doc.Field = siblingRecord.Field;
});
console.log(docTypeFields);