One Liner to Flatten Nested Object

One liner to flatten nested object

Here you go:

Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))

Summary: recursively create an array of one-property objects, then combine them all with Object.assign.

This uses ES6 features including Object.assign or the spread operator, but it should be easy enough to rewrite not to require them.

For those who don't care about the one-line craziness and would prefer to be able to actually read it (depending on your definition of readability):

Object.assign(
{},
...function _flatten(o) {
return [].concat(...Object.keys(o)
.map(k =>
typeof o[k] === 'object' ?
_flatten(o[k]) :
({[k]: o[k]})
)
);
}(yourObject)
)

Flatten an array with objects that have nested objects

You could spread the nested obejct.

const
data = [{ id: 1, someProp: "value of some prop", metaData: { metaId: 123, uuid: "2348_4354_dfgg_r343" } }, { id: 2, someProp: "value of some prop again", metaData: { metaId: 321, uuid: "9897_3543_ergl_j435" } }],
result = data.map(({ metaData, ...o }) => ({ ...o, ...metaData }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to flatten an object with nested objects in javascript

You can recursively build object any number of nested objects. So, this function is not your case dependent:

var enrollment = {user: {    id: 'string',    name: 'string'},finished: 'boolean',path: 'boolean'}
var enrollment2 = {user: { id: 'string', name: 'string'},test: { test1: { test2: { val0:'val0', test4: { //3rd level nested object for example val1: 'val1', val2: 'val2' } } }},finished: 'boolean',path: 'boolean'}
const flat = (obj, out) => { Object.keys(obj).forEach(key => { if (typeof obj[key] == 'object') { out = flat(obj[key], out) //recursively call for nesteds } else { out[key] = obj[key] //direct assign for values }
}) return out}
console.log(flat(enrollment, {}))console.log(flat(enrollment2, {}))

Best way to flatten JS object (keys and values) to a single depth array

You could just concat all keys and values. (It does not solve the type casting to number for keys.)

var object =  { 0: [1, 2, 3, 4] },    result = Object.keys(object).reduce(function (r, k) {        return r.concat(k, object[k]);    }, []);    console.log(result);

Flatten nested JavaScript object

Ideally a solution would require something to tell how far down to start classing the object as been a full object, a simple solution is just to pass the level you want. If you don't want to pass the level, you could do a check and if none of the properties have array's, then you would class this as a complete record, but of course that logic is something you would need to confirm.

If you want a generic version that works with multiple levels were you pass the level & using recursion you could do something like this ->

const a=[{a:1,b:2,c:[{x:10,y:20},{x:30,y:40}]},{a:3,b:4,c:[{x:50,y:60},{x:70,y:80}]}];

function flattern(a, lvl) { const r = []; function flat(a, l, o) { for (const aa of a) { o = {...o}; for (const [k, v] of Object.entries(aa)) { if (Array.isArray(v) && l < lvl) flat(v, l + 1, o); else o[k] = v; } if (l === lvl) r.push(o); } } flat(a, 1); return r;}
console.log(flattern(a, 2));//console.log(flattern(a, 1));

Javascript: Flatten each array item containing nested object

You can do something like:

const source = [  {    a: "x",    b: { b1: "x1", b2: "x2"}  },  {    a: "y",    b: { b1: "y1", b2: "y2"}  }]
const transformed = source.map(item => ({ ...item.b, a: item.a }));
console.log(transformed)

how to convert this nested object into a flat object?

You could use a recursive function to crawl the object and flatten it for you.

var test = {
a: 'jack',
b: {
c: 'sparrow',
d: {
e: 'hahaha'
}
}
};

function traverseAndFlatten(currentNode, target, flattenedKey) {
for (var key in currentNode) {
if (currentNode.hasOwnProperty(key)) {
var newKey;
if (flattenedKey === undefined) {
newKey = key;
} else {
newKey = flattenedKey + '.' + key;
}

var value = currentNode[key];
if (typeof value === "object") {
traverseAndFlatten(value, target, newKey);
} else {
target[newKey] = value;
}
}
}
}

function flatten(obj) {
var flattenedObject = {};
traverseAndFlatten(obj, flattenedObject);
return flattenedObject;
}

var flattened = JSON.stringify(flatten(test));
console.log(flattened);

Convert nested array of objects to a flat structure using recursion : Javascript

You can do it recursevly with passing the array reference by every recurse

const arr1 = [
{
name: "parent",
children: [
{
name: "child1",
children: [
{
name: "granchild1",
children: [],
class: "level-2 leaf",
config: {
name: "granchild1",
value1: false,
value2: false
}
}
],
class: "level-1 leaf",
config: {
name: "child1",
value1: false,
value2: false
}
},
{
name: "child2",
children: [],
class: "level-1 leaf",
config: {
name: "child2",
value1: false,
value2: false
}
}
],
class: "level-0 group",
config: {
name: "parent",
value1: false,
value2: false
}
}
];

let collect = (arr, result = []) => {

arr.forEach(prop => {
result.push({...prop.config})
collect(prop.children, result)
})
return result
}

let result = collect(arr1)

console.log(result)

How to flatten nested array in javascript?

This is an alternative to recursion (see jsfiddle here) and should accept any level of depth which avoids stack overflow.

var array = [[0, 1], [2, 3], [4, 5, [6, 7, [8, [9, 10]]]]];console.log(flatten(array), array); // does not mutate arrayconsole.log(flatten(array, true), array); // array is now empty
// This is done in a linear time O(n) without recursion// memory complexity is O(1) or O(n) if mutable param is set to falsefunction flatten(array, mutable) { var toString = Object.prototype.toString; var arrayTypeStr = '[object Array]'; var result = []; var nodes = (mutable && array) || array.slice(); var node;
if (!array.length) { return result; }
node = nodes.pop(); do { if (toString.call(node) === arrayTypeStr) { nodes.push.apply(nodes, node); } else { result.push(node); } } while (nodes.length && (node = nodes.pop()) !== undefined);
result.reverse(); // we reverse result to restore the original order return result;}

An elegant way to flatten an object

Just merge and delete every child property that's an instanceof Object.

let obj ={     temperature: null,     humidity: null,     pressure: null,     windspeed: null,     pollution: {        PM1: 1,        PM10: 2,        PM25: 3,  pollution: 4    }};
function flatten(obj){ obj = Object.assign({}, obj); for (let i in obj) if (obj[i] instanceof Object) { obj = Object.assign(obj, obj[i]);
// Prevent deletion of property i/"pollution", if it was not replaced by one of the child object's properties if (obj[i] === obj[i][i]) delete obj[i]; } return obj;}
let obj_flattened = flatten(obj);console.log(obj_flattened);


Related Topics



Leave a reply



Submit