You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js项目中创建含嵌套父对象的JavaScript对象求助

Fixing Nested Parent Category Structure in Node.js

Hey there! Let's get that nested category structure sorted out for you. From what you described, your current function returns an array of parent categories, but you want to nest the Residential object directly as a parent property inside the Furniture category object. Here's how to make that happen:

Step 1: Adjust Your Function to Nest the Parent Category

First, let's assume you're using async/await for database queries (standard in Node.js for async operations). The key is to fetch the parent category, then merge it into your subcategory object instead of returning it as a separate array.

Example Implementation (Raw SQL)

If you're using raw SQL with a library like mysql2 or pg, your function might look like this:

async function getCategoryWithNestedParent(subCategory) {
  // Fetch the parent category using the subcategory's parent_id
  const [parentCategories] = await db.query(
    'SELECT * FROM categories WHERE id = ?',
    [subCategory.parent_id]
  );
  
  // Grab the first (and only) parent category from the result array
  const parentCategory = parentCategories[0] || null;

  // Return the subcategory with the parent nested inside it
  return {
    ...subCategory, // Copy all subcategory properties
    parent: parentCategory // Add the nested parent object
  };
}

Example Implementation (ORM like Sequelize)

If you're using an ORM (which simplifies relationships), you can define an association and use include to fetch the parent in one query:

// First, define the association in your Category model
const Category = sequelize.define('Category', {
  name: DataTypes.STRING,
  parent_id: DataTypes.INTEGER
});

// Set up the self-referential association
Category.belongsTo(Category, { as: 'parent', foreignKey: 'parent_id' });

// Now the function to fetch with nested parent
async function getCategoryWithNestedParent(subCategoryId) {
  return Category.findByPk(subCategoryId, {
    include: { model: Category, as: 'parent' }
  });
}

Step 2: Test the Function

When you call this function with your Furniture category, you'll get the nested structure you want:

// Example call with your Furniture category
const furniture = { id: 2, name: 'Furniture', parent_id: 1 };
getCategoryWithNestedParent(furniture)
  .then(result => {
    console.log(result);
    // Output will be:
    // {
    //   id: 2,
    //   name: 'Furniture',
    //   parent_id: 1,
    //   parent: { id: 1, name: 'Residential', parent_id: null }
    // }
  })
  .catch(err => console.error('Error fetching category:', err));

Key Notes

  • Handle Edge Cases: Always account for cases where a subcategory might not have a parent (hence the || null in the raw SQL example).
  • Avoid Mutating Original Objects: Using the spread operator (...subCategory) creates a new object instead of modifying the original subcategory object, which is a good practice.

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:11:33