如何循环遍历嵌套对象并对其进行转换?

问题描述 投票:0回答:1

我有一个对象,可以有多层嵌套对象/数组、值。我需要能够循环它并转换它。例如

{
  arrayExample: [{
  _type: 0,
  value: 5
}, [{
  _type: 0,
  value: 1.1
}, {
  _type: 0,
  value: 1.2
}], {
  _type: 1,
  value: "hello"
}],
 simpleVal: {
   _type: 0,
  value: 10
 }
}

应该成为

{
  arrayExample: [5, [1.1, 1.2], new customClass("hello")],
  simpleVal: 10
}

_type
只是告诉我是否需要使用某些自定义类来解析该值。如果它是 0,我就按原样使用该值,如果不是,我会根据类型编号使用自定义类。

我最好需要一个迭代解决方案来避免堆栈溢出。

我尝试使用这个解决方案作为基础,因为它是迭代的,但我无法正确构造结果对象。

javascript loops recursion iteration javascript-objects
1个回答
0
投票

您可以检查数据是否是数组并再次调用它,或者根据

_type
获取正确的结构的对象。

class CustomClass {
    constructor(value) {
        this.value = value;
    }
}

const
    data = { arrayExample: [{ _type: 0, value: 5 }, [{ _type: 0, value: 1.1 }, { _type: 0, value: 1.2 }], { _type: 1, value: "hello" }], simpleVal: { _type: 0, value: 10 } },
    getTyped = ({ _type, value }) => {
        switch (_type) {
            case 0: return value;
            case 1: return new CustomClass(value);
        }
    },
    getValue = v => Array.isArray(v)
        ? v.map(getValue)
        : getTyped(v),
    result = Object.fromEntries(Object
        .entries(data)
        .map(([k, v]) => [k, getValue(v)])
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

© www.soinside.com 2019 - 2024. All rights reserved.