
在前端开发中,我们经常需要对从后端获取或本地存储的复杂数据结构进行转换,以适应UI展示或进一步的数据处理需求。本例中,我们面临两个原始数组:
我们的目标是生成一个名为 final 的新数组,其结构如下:
const final = [
{
"cartId": "full", // 来自 boxes 数组中每个对象的 cartType 字段
"itemsCategory": [ // 这是一个数组,包含每个物品的 categoryId
{
"categoryId": "645bbe9141332374a05919d2" // 来自 items 数组中匹配物品的 _id
},
// ... 更多 categoryId 对象
]
},
// ... 更多 cartId 对象
];具体转换规则如下:
为了实现上述复杂的嵌套数据转换和查找,我们将主要利用以下两个高阶数组方法:
立即学习“Java免费学习笔记(深入)”;
我们将分步构建解决方案,并提供完整的代码示例。
首先,我们定义原始的 boxes 和 items 数组,以便于理解和测试。
const boxes = [
{
"trolleyNo": "345A",
"trolleyItems": [
{ "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bar Cart - Liquor, Liqueur", "value": "Bar Cart - Liquor, Liqueur", "label": "Bar Cart - Liquor, Liqueur" },
{ "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bar Cart - Beer & Wine", "value": "Bar Cart - Beer & Wine", "label": "Bar Cart - Beer & Wine" },
{ "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bread Basket & Tongs", "value": "Bread Basket & Tongs", "label": "Bread Basket & Tongs" },
{ "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Crew Store - Cookies, juices, etc", "value": "Crew Store - Cookies, juices, etc", "label": "Crew Store - Cookies, juices, etc" }
],
"cartType": "fullCart",
"index": "FC-093"
},
{
"trolleyNo": "560S",
"trolleyItems": [
{ "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bar Cart - Beer & Wine", "value": "Bar Cart - Beer & Wine", "label": "Bar Cart - Beer & Wine" },
{ "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Bread Basket & Tongs", "value": "Bread Basket & Tongs", "label": "Bread Basket & Tongs" },
{ "key": "02f2c8e0-cd40-11ed-8563-092a964acecc", "name": "Crockery - Full Plates", "value": "Crockery - Full Plates", "label": "Crockery - Full Plates" }
],
"cartType": "halfCart",
"index": "FC-093"
}
];
const items = [
{ "_id": "646d96f669cad73dc5d14a25", "name": "Bar Cart - Beer & Wine", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" },
{ "_id": "646d96f669cad73dc5d14a24", "name": "Bar Cart - Liquor, Liqueur", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" },
{ "_id": "646d96f669cad73dc5d14a2b", "name": "Bread Basket & Tongs", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" },
{ "_id": "646d96f669cad73dc5d14a2d", "name": "Crew Meals", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" },
{ "_id": "646d96f669cad73dc5d14a31", "name": "Crew Store - Cookies, juices, etc", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" },
{ "_id": "646d96f669cad73dc5d14a32", "name": "Crockery - Full Plates", "customerId": "02f2c8e0-cd40-11ed-8563-092a964acecc" },
];const final = boxes.map(box => {
return {
cartId: box.cartType,
itemsCategory: box.trolleyItems.map(titem => {
// 在 items 数组中查找与 titem.name 匹配的 item
const matchedItem = items.find(item => item.name === titem.name);
return {
// 如果找到匹配项,则使用其 _id;否则为 undefined
categoryId: matchedItem ? matchedItem._id : undefined
};
})
};
});
console.log(JSON.stringify(final, null, 2));运行上述代码,将得到符合预期的 final 数组:
[
{
"cartId": "fullCart",
"itemsCategory": [
{
"categoryId": "646d96f669cad73dc5d14a24"
},
{
"categoryId": "646d96f669cad73dc5d14a25"
},
{
"categoryId": "646d96f669cad73dc5d14a2b"
},
{
"categoryId": "646d96f669cad73dc5d14a31"
}
]
},
{
"cartId": "halfCart",
"itemsCategory": [
{
"categoryId": "646d96f669cad73dc5d14a25"
},
{
"categoryId": "646d96f669cad73dc5d14a2b"
},
{
"categoryId": "646d96f669cad73dc5d14a32"
}
]
}
]外层 map (boxes.map(...)):
内层 map (box.trolleyItems.map(...)):
items.find(item => item.name === titem.name):
matchedItem ? matchedItem._id : undefined:
本教程强调了根据问题描述使用 name 字段进行匹配的重要性。在实际开发中,务必仔细核对数据模型和业务需求,确保选择正确的字段进行关联查找。错误的匹配逻辑会导致数据转换结果不准确。
上述解决方案对于 boxes 和 items 数组规模较小的情况非常有效且易于理解。然而,如果 items 数组非常庞大(例如,包含数万甚至数十万个物品),在内层 map 中每次都对 items 数组执行 find 操作会导致性能问题。因为 find 的时间复杂度在最坏情况下是 O(N)(N 是 items 数组的长度)。如果 boxes 数组和 trolleyItems 数组也很长,总复杂度可能会达到 O(M * K * N),其中 M 是 boxes 长度,K 是 trolleyItems 的最大长度。
为了优化性能,我们可以考虑在转换开始前,将 items 数组预处理成一个哈希表(或 Map 对象),以 name 作为键,_id 作为值。这样,后续的查找操作就可以从 O(N) 降低到平均 O(1) 的时间复杂度。
优化示例:
// 步骤1: 预处理 items 数组,创建 Map 进行快速查找
const itemsMap = new Map();
items.forEach(item => {
itemsMap.set(item.name, item._id);
});
const finalOptimized = boxes.map(box => {
return {
cartId: box.cartType,
itemsCategory: box.trolleyItems.map(titem => {
// 从 Map 中直接获取 categoryId,查找速度更快
const categoryId = itemsMap.get(titem.name);
return {
categoryId: categoryId // 如果找不到,get() 返回 undefined
};
})
};
});
console.log(JSON.stringify(finalOptimized, null, 2));通过这种优化,我们将查找 categoryId 的操作从线性搜索变成了常数时间查找,显著提升了大数据量下的性能。
当 trolleyItem.name 在 items 数组中没有找到对应项时,matchedItem 将为 undefined,从而 categoryId 也会是 undefined。根据业务需求,您可能需要不同的处理方式:
itemsCategory: box.trolleyItems.map(titem => {
const categoryId = itemsMap.get(titem.name);
return { categoryId: categoryId };
}).filter(item => item.categoryId !== undefined) // 过滤掉 categoryId 为 undefined 的项categoryId: itemsMap.get(titem.name) || null // 如果找不到,则为 null
以上就是JavaScript数组对象深度转换:从嵌套结构生成目标数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号