es6 数组对象扁平化

9cqqzkmx
  • 1
新手上路,请多包涵

有对象如下

var object = {
            a: 1,
            b: 2,
            c: {
                aa: 11,
                bb: 22
            }
        }

怎么变化后能输出

var object = {
        a: 1,
        b: 2,
        aa: 11,
        bb: 22
}
回复
阅读 829
5 个回答
var object = {
    a: 1,
    b: 2,
    c: {
        aa: 11,
        bb: 22
    }
};
const objFlat = (obj, res = {}) => {
    Object.keys(obj).map(k => {
        obj[k].constructor === Object ? objFlat(obj[k], res) : res[k] = obj[k];
    });
    return res;
};
console.log(objFlat(object));
var object = {
            a: 1,
            b: 2,
            c: {
                aa: 11,
                bb: 22
            }
        }

let isType = (obj,type)=>Object.prototype.toString.call(obj) === `[object ${type}]`;
let treeToArr=(obj)=>Object.entries(obj).reduce((acc,[key,val])=>Object.assign(acc ,isType(val, 'Object') ? treeToArr(val) : Object.fromEntries([[key,val]])),{});
treeToArr(object);
{a: 1, b: 2, aa: 11, bb: 22}
const object = {
    a: 1,
    b: 2,
    c: {
        aa: 11,
        bb: 22
    },
    d: null,
    e: [1, 2, 3]
};

function flatObject(source, target = {}) {
    Object.entries(source)
        .forEach(([k, v]) => {
            if (v && typeof v === "object" && !Array.isArray(v)) {
                flatObject(v, target);
            } else {
                target[k] = v;
            }
        });
    return target;
}

const r = flatObject(object);
console.log(r);
// { a: 1, b: 2, aa: 11, bb: 22, d: null, e: [ 1, 2, 3 ] }

使用一个递归即可,关键就是判断当前的 key 是不是对象。

var object = {
  a: 1,
  b: 2,
  c: {
    aa: 11,
    bb: 22
  }
}

const flattenObject = (object) => 
  Object.keys(object).reduce((target, key) => ({
    ...target,
    ...(typeof object[key] === 'object' ? flattenObject(object[key]) : { [key]: object[key]})
  }), {});

console.log(flattenObject(object));

https://codepen.io/pantao/pen...

你知道吗?

宣传栏