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

JavaScript嵌套数组对象属性添加与buildSimList结构转换方法咨询

Solution for Building a Structurally Identical Array with Transformed Data

Hey there! Let's break this down step by step since you already have recursion basics under your belt—great start. Below are practical, intuitive solutions for your buildSimList function, plus methods to add properties to nested objects.

1. Manual Recursive Implementation

Since you’re comfortable with recursive traversal, this is the most flexible approach. The core idea is: traverse each element, recursively process subarrays, and transform objects while preserving the original structure.

Let’s use a concrete example. Suppose your original data looks like this:

const originalData = [
  { id: 1, name: "Item 1", children: [{ id: 11, name: "Subitem 1" }] },
  { id: 2, name: "Item 2" }
];

We want to convert it to a structure where id becomes value, children becomes items, and we add a label field. Here’s how to do it:

function buildSimList(arr) {
  return arr.map(item => {
    // Handle objects: transform format and recurse on nested arrays
    if (typeof item === 'object' && !Array.isArray(item)) {
      const transformedObj = {
        value: item.id,
        label: item.name
      };
      // Preserve nested structure by recursively processing children
      if (item.children) {
        transformedObj.items = buildSimList(item.children);
      }
      return transformedObj;
    }
    // Handle nested arrays (redundant here but safe for edge cases)
    else if (Array.isArray(item)) {
      return buildSimList(item);
    }
    // Return non-object/array elements as-is
    return item;
  });
}

// Get your target structure
const result = buildSimList(originalData);

This gives you full control over the transformation logic and guarantees the output matches the original array’s structure exactly.

2. Simplified Solution with Lodash

If you prefer using a library to reduce boilerplate, _.cloneDeepWith is perfect. It deep-clones the original structure and lets you define custom transformations for elements.

Using the same original data example:

const _ = require('lodash');

function buildSimListWithLodash(arr) {
  return _.cloneDeepWith(arr, (value) => {
    // Only transform plain objects (arrays are handled automatically via recursion)
    if (_.isPlainObject(value)) {
      const transformed = {
        value: value.id,
        label: value.name
      };
      // Preserve nested subarrays—lodash will recursively process them
      if (value.children) transformed.items = value.children;
      return transformed;
    }
    // Return undefined to let lodash use default cloning for other types
  });
}

Lodash handles edge cases like null or special objects out of the box, so this is a clean, low-effort option.

3. Methods to Add Properties to All Nested Objects

Here are two common approaches to add properties to every object in a nested array:

Method 1: Immutable Manual Recursion (No Original Data Modification)

function addNestedProperty(arr, propKey, propValue) {
  return arr.map(item => {
    if (typeof item === 'object' && !Array.isArray(item)) {
      // Return a new object with the added property, plus recursively processed children
      return {
        ...item,
        [propKey]: propValue,
        ...(item.children && { children: addNestedProperty(item.children, propKey, propValue) })
      };
    }
    else if (Array.isArray(item)) {
      return addNestedProperty(item, propKey, propValue);
    }
    return item;
  });
}

// Example: Add an `isSelected` property set to false for all nested objects
const updatedData = addNestedProperty(originalData, 'isSelected', false);

Method 2: Lodash Solutions

For an immutable approach, reuse _.cloneDeepWith:

function addPropertyWithLodash(arr, propKey, propValue) {
  return _.cloneDeepWith(arr, (value) => {
    if (_.isPlainObject(value)) {
      return { ...value, [propKey]: propValue };
    }
  });
}

If you don’t mind modifying the original data, use a recursive traversal to mutate objects directly:

function addPropertyMutably(arr, propKey, propValue) {
  arr.forEach(item => {
    if (typeof item === 'object' && !Array.isArray(item)) {
      item[propKey] = propValue;
      // Recurse on nested children if they exist
      if (item.children) addPropertyMutably(item.children, propKey, propValue);
    }
    else if (Array.isArray(item)) {
      addPropertyMutably(item, propKey, propValue);
    }
  });
}

// Call to modify the original array
addPropertyMutably(originalData, 'isSelected', false);

内容的提问来源于stack exchange,提问作者ey dee ey em

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:31:43