使用 .map 循环对象数组并将新数组存储在对象值中
Using .map to loop array of objects and store new array in object value
我目前正在从对象数组的数据库中获取数据。我需要将这些对象重新格式化以与我们正在使用的 UI 包一起使用,该包要求这些对象以特定方式显示。主数组应如下所示:
[{
trim: 123,
id: 123,
children: [{
trim: 123,
id: 123,
}],
}]
我成功地遍历了主数组数据并使用 .map 将其重新格式化为一个新数组;但是,除了在主数组的每个对象中找到的 children key 之外,我在做同样的事情时遇到了问题。想知道是否有人可以帮助我找出正确的方法来做到这一点。我将在下面添加我当前的代码,如果需要,我将能够阐明更多内容。
if (this.$store.state.models.models) { // this is checking for the main array coming from the database
const reformattedModels = this.$store.state.models.models.map((model) => {
const tableModel = {
trim: model.name,
id: model.id,
children: // Need to loop here to reformat array of objects that goes for the children key,
};
return tableModel;
});
return reformattedModels;
}
我需要为子键遍历的数组是从后端在主数组中找到的键之一。它叫做“修剪”,看起来像这样:
[{
name: 123,
id: 123,
}]
创建对函数的引用并递归调用它:
if (this.$store.state.models.models) {
// store the function
const mapper = model => ({
trim: model.name,
id: model.id,
// use it for children, if there are any
children: model.children?.map(mapper)
});
// use it for the models
return this.$store.state.models.models.map(mapper);
}
仅当 model.children != undefined
时,我才使用 optional chaining (?.
) 调用 .map()
我目前正在从对象数组的数据库中获取数据。我需要将这些对象重新格式化以与我们正在使用的 UI 包一起使用,该包要求这些对象以特定方式显示。主数组应如下所示:
[{
trim: 123,
id: 123,
children: [{
trim: 123,
id: 123,
}],
}]
我成功地遍历了主数组数据并使用 .map 将其重新格式化为一个新数组;但是,除了在主数组的每个对象中找到的 children key 之外,我在做同样的事情时遇到了问题。想知道是否有人可以帮助我找出正确的方法来做到这一点。我将在下面添加我当前的代码,如果需要,我将能够阐明更多内容。
if (this.$store.state.models.models) { // this is checking for the main array coming from the database
const reformattedModels = this.$store.state.models.models.map((model) => {
const tableModel = {
trim: model.name,
id: model.id,
children: // Need to loop here to reformat array of objects that goes for the children key,
};
return tableModel;
});
return reformattedModels;
}
我需要为子键遍历的数组是从后端在主数组中找到的键之一。它叫做“修剪”,看起来像这样:
[{
name: 123,
id: 123,
}]
创建对函数的引用并递归调用它:
if (this.$store.state.models.models) {
// store the function
const mapper = model => ({
trim: model.name,
id: model.id,
// use it for children, if there are any
children: model.children?.map(mapper)
});
// use it for the models
return this.$store.state.models.models.map(mapper);
}
仅当 model.children != undefined
?.
) 调用 .map()