flatten object js code example

Example 1: flatten array object javascript

var flattenArray = function(data) {
	return data.reduce(function iter(r, a) {
		if (a === null) {
			return r;
		}
		if (Array.isArray(a)) {
			return a.reduce(iter, r);
		}
		if (typeof a === 'object') {
			return Object.keys(a).map(k => a[k]).reduce(iter, r);
		}
		return r.concat(a);
	}, []);
}
console.log(flattenArray(data))

//replace data with your array

Example 2: javascript flat object

function dotify(obj) {
    const res = {};
    function recurse(obj, current) {
        for (const key in obj) {
            const value = obj[key];
            if(value != undefined) {
                const newKey = (current ? current + '.' + key : key);
                if (value && typeof value === 'object') {
                    recurse(value, newKey);
                } else {
                    res[newKey] = value;
                }
            }
        }
    }
    recurse(obj);
    return res;
}
dotify({'a':{'b1':{'c':1},'b2':{'c':1}}}) //{'a.b1.c':1,'a.b2.c':1}