[英]Looping through nested array of objects, matching to another array of objects
我是 Javascript 的新手,我试图遍历一个嵌套的对象数组,并根据第一个对象的属性过滤第二个对象数组。
这是两个数组的结构:
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: [ {...}, {...} ] }
}
...
]
我正在尝试通过displayArr
中的table_name
和field_name
过滤schemaArr
。 当有匹配时,我想将description
和display_name
提供给 displayArr。 例如:
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
中可能引用了任意数量的表。
对我来说,鉴于这些对象是嵌套的,这是一个更复杂的映射/过滤情况。 我想知道如何正确有效地利用 map、过滤器和/或 forEach。
预先感谢您的帮助。 真的很感激。
Object.values()可用于获取displayArr
object 的值, forEach()可用于对其进行迭代。
find()方法可用于在schemaArr
中查找具有table_name
的表。 如果 table 存在,则可以再次使用find()方法查找具有 item 的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;
}
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.