map function for objects (instead of arrays)

前端 未结 30 2620
无人及你
无人及你 2020-11-22 04:23

I have an object:

myObject = { \'a\': 1, \'b\': 2, \'c\': 3 }

I am looking for a native method, similar to Array.prototype.map

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 04:57

    const mapObject = (targetObject, callbackFn) => {
        if (!targetObject) return targetObject;
        if (Array.isArray(targetObject)){
            return targetObject.map((v)=>mapObject(v, callbackFn))
        }
        return Object.entries(targetObject).reduce((acc,[key, value]) => {
            const res = callbackFn(key, value);
            if (!Array.isArray(res) && typeof res ==='object'){
                return {...acc, [key]: mapObject(res, callbackFn)}
            }
            if (Array.isArray(res)){
                return {...acc, [key]: res.map((v)=>mapObject(v, callbackFn))}
            }
            return {...acc, [key]: res};
        },{})
    };
    const mapped = mapObject(a,(key,value)=> {
        if (!Array.isArray(value) && key === 'a') return ;
        if (!Array.isArray(value) && key === 'e') return [];
        if (!Array.isArray(value) && key === 'g') return value * value;
        return value;
    });
    console.log(JSON.stringify(mapped)); 
    // {"b":2,"c":[{"d":2,"e":[],"f":[{"g":4}]}]}
    

    This function goes recursively through the object and arrays of objects. Attributes can be deleted if returned undefined

提交回复
热议问题