我是Java语言的新手,正在尝试遍历一个嵌套的对象数组,并根据第一个对象的属性过滤第二个对象数组。
这都是数组的结构:
const displayArr = {
sections: {
section_1: [
{
style: "single_select_cmp",
definition: {
table_name: "table_1",
field_name: "organization",
}
},
],
section_2: [
{
style: "single_select_cmp",
definition: {
table_name: "table_1",
field_name: "title",
}
},
]
}
};
const schemaArr = [
{
table_1: {
columns: [
{
description: "Tracking Number Desc",
display_name: "Tracking Number",
display_type: "number",
field: "tracking_number",
type: "int"
},
{
description: "Title Desc",
display_name: "Title",
display_type: "multiple lines of text",
field: "title",
type: "text"
},
{
description: "Description Desc",
display_name: "Description",
display_type: "multiple lines of text",
field: "description",
type: "text"
},
{
description: "Organization Desc",
display_name: "Organization",
display_type: "single line of text",
field: "organization",
type: "text"
}
]
}
},
{
table_2: { columns: [ {...}, {...} ] }
},
{
table_3: { columns: [ {...}, {...} ] }
}
...
]
我正在尝试按schemaArr
中的table_name
和field_name
过滤displayArr
。如果存在匹配项,我想向displayArr提供description
和display_name
。例如:
const displayArr = {
sections: {
section_1: [
{
style: "single_select_cmp",
definition: {
table_name: "table_1",
field_name: "organization",
description: "Organization Description", //***
display_name: "Organization" //***
}
},
],
section_2: [
{
style: "single_select_cmp",
definition: {
table_name: "table_1",
field_name: "title",
description: "Title Description", //***
display_name: "Title" //***
}
},
]
}
};
在此示例中,我只是从table_1
中提取,但是displayArr
中可能引用了许多表。
对我来说,鉴于这些对象是嵌套的,因此这是一种更为复杂的映射/过滤情况。我想知道如何正确有效地利用地图,过滤器和/或forEach。
预先感谢您的帮助!真的很感激。
答案 0 :(得分:1)
Object.values()可用于获取displayArr
对象的值,而forEach()可用于对其进行迭代。
find()方法可用于在table_name
中以schemaArr
查找表。如果存在表,则可以再次使用find()方法来查找包含项目的field_name
的列。
然后displayArr
对象的定义项可以使用找到的此列值进行更新。
Object.values(displayArr.sections).forEach(section => {
section.forEach(item => {
let table = schemaArr.find(table => table[item.definition.table_name]);
if (table) {
// Find column by field_name.
let obj = table[item.definition.table_name].columns.find(column => column.field === item.definition.field_name);
if (obj) {
// Update definition.
item.definition.description = obj.description;
item.definition.display_name = obj.display_name;
}
}
});
});