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

如何实现嵌套对象任意层级字段值切换函数?无需解析字符串与递归

Clean Solution: Use Functional Path Access + Proxy (or Vue Computed Properties)

Great question! Parsing string paths or recursively digging through objects always feels hacky—let’s solve this with approaches that let you work with nested properties like you normally would, no parsing or recursion required.

Option 1: Proxy-Based Path Catching (Vanilla JS)

We can use JavaScript's Proxy API to create a tiny utility that captures nested property paths as you chain them, then use that to toggle the value directly. No string parsing, no recursive object traversal—just native property access syntax.

// Helper to create a proxy that tracks nested property paths
function pathProxy(obj, currentPath = []) {
  return new Proxy({}, {
    get(_, prop) {
      // Expose methods to get/set the tracked property
      if (prop === "$get") return () => currentPath.reduce((curr, key) => curr[key], obj);
      if (prop === "$set") return (val) => {
        const parent = currentPath.slice(0, -1).reduce((curr, key) => curr[key], obj);
        parent[currentPath.at(-1)] = val;
        return val;
      };
      // Continue building the path
      return pathProxy(obj, [...currentPath, prop]);
    }
  });
}

// Your toggle function
function toggle(obj, pathAccessor) {
  const proxy = pathAccessor(pathProxy(obj));
  proxy.$set(!proxy.$get());
  // Customize toggle logic here if you're not switching booleans
}

// Usage example
const outer = { inner: { price: true } };

// Call toggle with a chain that matches your nested property
toggle(outer, p => p.inner.price);
console.log(outer.inner.price); // false
toggle(outer, p => p.inner.price);
console.log(outer.inner.price); // true

How this works:

  • The pathProxy creates a proxy that tracks every property you chain (like p.inner.price).
  • When you call $get() or $set(), it uses the tracked path to directly access/modify the nested property—no recursion, no string splitting.
  • The toggle function just uses this proxy to flip the value cleanly.

Option 2: Vue Computed Properties (Vue Projects)

If you're working in Vue, computed properties with getters/setters are made for this scenario. They let you map a nested property to a top-level "virtual" property that you can toggle directly.

<template>
  <button @click="togglePrice">Toggle Price</button>
</template>

<script setup>
import { ref, computed } from 'vue';

const outer = ref({ inner: { price: true } });

// Computed property that maps to the nested field
const price = computed({
  get() {
    return outer.value.inner.price;
  },
  set(newVal) {
    outer.value.inner.price = newVal;
  }
});

// Toggle function is dead simple
function togglePrice() {
  price.value = !price.value;
}
</script>

Why this is perfect:

  • Vue handles all the nested property access under the hood—you never have to parse paths or traverse objects manually.
  • Toggling is just flipping the computed property's value, which automatically updates the original nested object.

Both approaches let you work with nested properties using native syntax, avoiding the messy string parsing or recursion you wanted to skip.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:23:05