flatten object to array javascript 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: flatten nested array javascript
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
Example 3: 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 4: js .flat
const arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
const merge3 = arrays.flat(1);
console.log(merge3);