javascript flatten object 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))
Example 2: make a flat object from object of object list
var object = { 0: [1, 2, 3, 4] },
result = Object.keys(object).reduce(function (r, k) {
return r.concat(k, object[k]);
}, []);
console.log(result);
Example 3: object flatten js
Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))
Example 4: flatten nested object js
Object.assign(
{},
...function _flatten(o) {
return [].concat(...Object.keys(o)
.map(k =>
typeof o[k] === 'object' ?
_flatten(o[k]) :
({[k]: o[k]})
)
);
}(yourObject)
)
Example 5: 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}}})
Example 6: object flatten js
Object.assign(
{},
...function _flatten(o) {
return [].concat(...Object.keys(o)
.map(k =>
typeof o[k] === 'object' ?
_flatten(o[k]) :
({[k]: o[k]})
)
);
}(yourObject)
)