Transformation of nested object - javascript

I am new to JavaScript and Node JS
want to transform the following nested object with student
Data:
[{
"id": 1,
"name": "A",
"children": [{
"id": 2,
"name": "B",
"children": [{
"id": 3,
"name": "C"
},
{
"id": 4,
"name": "D"
}
]
}]
}]
to
Expected:
[{
"student": {
"id": 1,
"name": "A"
},
"children": [{
"student": {
"id": 2,
"name": "B"
},
"children": [{
"student": {
"id": 3,
"name": "C"
}
},
{
"student": {
"id": 4,
"name": "D"
}
}
]
}]
}]

I guess you are seeking a solution for an array with multiple student objects. So you can use the map method to modify them.
const original = [{
"id": 1,
"name": "A",
"children": [{
"id": 2,
"name": "B",
"children": [{
"id": 3,
"name": "C"
},
{
"id": 4,
"name": "D"
}
]
}]
}]
const modified = original.map(stu => {
return {
student: {
id: stu.id,
name: stu.name,
},
children: stu.children
}
})

Related

How to filter through children of array of objects and then return parent with updated children?

I'm trying to filter through an array of objects it's children then update the children and return the parent with updated children.
Example array of objects:
[
{
"id": 1,
"name": "group1",
"users": [
{
"id": 1,
"name": "Mike"
},
{
"id": 2,
"name": "Steve"
},
{
"id": 3,
"name": "John"
}
]
},
{
"id": 2,
"name": "group2",
"users": [
{
"id": 4,
"name": "Phill"
},
{
"id": 5,
"name": "Joe"
},
{
"id": 6,
"name": "Dominik"
}
]
}
]
I've got an input in React where someone can type in a name of an user, then i'd like to only show the users with that name while keeping the group that they're in.
For example, if the input is 'Mike' I would like the result to be:
[
{
"id": 1,
"name": "group1",
"users": [
{
"id": 1,
"name": "Mike"
}
]
},
{
"id": 2,
"name": "group2",
"users": []
}
]
You can use map() and filter() to do that.
let arr = [ { "id": 1, "name": "group1", "users": [ { "id": 1, "name": "Mike" }, { "id": 2, "name": "Steve" }, { "id": 3, "name": "John" } ] }, { "id": 2, "name": "group2", "users": [ { "id": 4, "name": "Phill" }, { "id": 5, "name": "Joe" }, { "id": 6, "name": "Dominik" } ] } ];
function filterUsers(arr, name) {
return arr.map(obj => {
return {
...obj,
"users": obj.users.filter(user => user.name === name)
};
});
}
console.log(filterUsers(arr, "Mike"));

How do I flatten a (forest of) trees?

I have a forest of trees of arbitrary height, more or less like this:
let data = [
{ "id": 2, "name": "AAA", "parent_id": null, "short_name": "A" },
{
"id": 10, "name": "BBB", "parent_id": null, "short_name": "B", "children": [
{
"id": 3, "name": "CCC", "parent_id": 10, "short_name": "C", "children": [
{ "id": 6, "name": "DDD", "parent_id": 3, "short_name": "D" },
{ "id": 5, "name": "EEE", "parent_id": 3, "short_name": "E" }
]
},
{
"id": 4, "name": "FFF", "parent_id": 10, "short_name": "F", "children": [
{ "id": 7, "name": "GGG", "parent_id": 4, "short_name": "G" },
{ "id": 8, "name": "HHH", "parent_id": 4, "short_name": "H" }
]
}]
}
];
And I'm trying to produce a representation of all the root-to-leaves paths, something like this
[
[
{
"id": 2,
"name": "AAA"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 6,
"name": "DDD"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 5,
"name": "EEE"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 7,
"name": "GGG"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 8,
"name": "HHH"
}
]
]
So I wrote the following code:
function flattenTree(node, path = []) {
if (node.children) {
return node.children.map(child => flattenTree(child, [...path, child]));
} else {
let prefix = path.slice(0, path.length - 1).map(n => ({ id: n.id, name: n.short_name }));
let last = path[path.length - 1];
return [...prefix, { id: last.id, name: last.name } ];
}
}
let paths = data.map(n => flattenTree(n, [n]));
but paths comes out with extra nesting, like this:
[
[
{
"id": 2,
"name": "AAA"
}
],
[
[
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 6,
"name": "DDD"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 3,
"name": "C"
},
{
"id": 5,
"name": "EEE"
}
]
],
[
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 7,
"name": "GGG"
}
],
[
{
"id": 10,
"name": "B"
},
{
"id": 4,
"name": "F"
},
{
"id": 8,
"name": "HHH"
}
]
]
]
]
I lost count of the many ways in which I tried to fix this, but it does look like the algorithm should not produce the extra nesting -- or my eyes are just so crossed by now that I couldn't see my mistake if someone stuck their finger on it.
Can someone help? Feel free to peruse this JSFiddle https://jsfiddle.net/png7x9bh/66/
The extra nestings are created by map. map just wraps the results into an array and returns them, it doesn't care if it is called on child nodes or not. Use reduce and just concat (or push, whatever suits your performance) the results into the first level array directly:
let data = [{"id":2,"name":"AAA","parent_id":null,"short_name":"A"},{"id":10,"name":"BBB","parent_id":null,"short_name":"B","children":[{"id":3,"name":"CCC","parent_id":10,"short_name":"C","children":[{"id":6,"name":"DDD","parent_id":3,"short_name":"D"},{"id":5,"name":"EEE","parent_id":3,"short_name":"E"}]},{"id":4,"name":"FFF","parent_id":10,"short_name":"F","children":[{"id":7,"name":"GGG","parent_id":4,"short_name":"G"},{"id":8,"name":"HHH","parent_id":4,"short_name":"H"}]}]}];
function flattenTree(node, path = []) {
let pathCopy = Array.from(path);
pathCopy.push({id: node.id, name: node.name});
if(node.children) {
return node.children.reduce((acc, child) => acc.concat(flattenTree(child, pathCopy)), []);
}
return [pathCopy];
}
let result = data.reduce((result, node) => result.concat(flattenTree(node)), []);
console.log(JSON.stringify(result, null, 3));

Using angularjs forEach loops

I am getting this type of json in my $scope of angularjs:
$scope.someStuff = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [
{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
}
I want to use angularjs forEach loop and i want to get only category name,
My expected output:
[{"name":"software"}, {"name":"hardware"}, {"name":"waterwash"}]
You can use Array.map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
$scope.someStuff.categoryservices.map((x) => { return { name: x.category.name}})
var obj = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
};
console.log(obj.categoryservices.map((x) => {
return {
name: x.category.name
}
}))
You can use map method by passing a callback function as parameter.
const someStuff = { "id": 2, "service": "bike", "min": "22", "per": "100", "tax": "1", "categoryservices": [ { "id": 32, "category": { "id": 1, "name": "software" } }, { "id": 33, "category": { "id": 2, "name": "hardware" } }, { "id": 34, "category": { "id": 3, "name": "waterwash" } } ] }
let array = someStuff.categoryservices.map(function({category}){
return {'name' : category.name}
});
console.log(array);

Build a map using values of multiple objects in an array javascript

I need to build a map "A" from an existing array of objects. However the key value pairs on Map A are from the values of existing Object keys "id" and "cap".
Is it possible to read the values of 2 keys and store as an object
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
},{
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}
]
}]
My map needs to be like this
{ "1" : [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}],
"2" : [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}
Use Array#reduce to achieve the results like below:
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}, {
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}];
var ans = items.reduce(function(v, i) {
v[i.id] = i.cap;
return v;
}, {});
console.log(ans);
You can do this using a simple loop on the original array, and defining a new key: value pair into the object.
// Create the map
var map = {}
// For every 'item' within the 'items' array
items.forEach(item => {
// Map the item ID to the item.cap array
map[item.id] = item.cap
}
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}, {
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
}]
var map = {}
items.forEach(item => {
map[item.id] = item.cap
})
console.log(map)
Using ES6 Array.from() method.
var items = [{
"id": 1,
"name": "Primary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}]
},{
"id": 2,
"name": "Secondary",
"cap": [{
"id": "1",
"name": "1s"
}, {
"id": "2",
"name": "T2s"
}
]
}];
var obj = {};
var res = Array.from(items, x => obj[x.id] = x.cap);
console.log(obj);

Deep Flatten JavaScript Object Recursively

Data:
var data = [
{
"id": 1,
"level": "1",
"text": "Sammy",
"type": "Item",
"items": [
{
"id": 11,
"level": "2",
"text": "Table",
"type": "Item",
"items": [
{
"id": 111,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 112,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
}
]
},
{
"id": 12,
"level": "2",
"text": "Chair",
"type": "Item",
"items": [
{
"id": 121,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 122,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
}
]
}
]
},
{
"id": 2,
"level": "1",
"text": "Sundy",
"type": "Item",
"items": [
{
"id": 21,
"level": "2",
"text": "MTable",
"type": "Item",
"items": [
{
"id": 211,
"level": "3",
"text": "MTDog",
"type": "Item",
"items": null
},
{
"id": 212,
"level": "3",
"text": "MTCat",
"type": "Item",
"items": null
}
]
},
{
"id": 22,
"level": "2",
"text": "MChair",
"type": "Item",
"items": [
{
"id": 221,
"level": "3",
"text": "MCDog",
"type": "Item",
"items": null
},
{
"id": 222,
"level": "3",
"text": "MCCat",
"type": "Item",
"items": null
}
]
}
]
},
{
"id": 3,
"level": "1",
"text": "Bruce",
"type": "Folder",
"items": [
{
"id": 31,
"level": "2",
"text": "BTable",
"type": "Item",
"items": [
{
"id": 311,
"level": "3",
"text": "BTDog",
"type": "Item",
"items": null
},
{
"id": 312,
"level": "3",
"text": "BTCat",
"type": "Item",
"items": null
}
]
},
{
"id": 32,
"level": "2",
"text": "Chair",
"type": "Item",
"items": [
{
"id": 321,
"level": "3",
"text": "BCDog",
"type": "Item",
"items": null
},
{
"id": 322,
"level": "3",
"text": "BCCat",
"type": "Item",
"items": null
}
]
}
]
}
];
Code:
var fdr = [];
var fd = function(n) {
if (n.items) {
_.forEach(n.items, function (value){
fd(value);
});
}
fdr.push(n);
};
_.forEach(data, fd);
console.log(fdr);
Desired output:
var data = [
{
"id": 1,
"level": "1",
"text": "Sammy",
"type": "Item",
"items": []
},
{
"id": 11,
"level": "2",
"text": "Table",
"type": "Item",
"items": []
},
{
"id": 111,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 112,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
},
{
"id": 12,
"level": "2",
"text": "Chair",
"type": "Item",
"items": []
},
{
"id": 121,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 122,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
},
{
"id": 2,
"level": "1",
"text": "Sundy",
"type": "Item",
"items": []
},
{
"id": 21,
"level": "2",
"text": "MTable",
"type": "Item",
"items": []
},
{
"id": 211,
"level": "3",
"text": "MTDog",
"type": "Item",
"items": null
},
{
"id": 212,
"level": "3",
"text": "MTCat",
"type": "Item",
"items": null
},
{
"id": 22,
"level": "2",
"text": "MChair",
"type": "Item",
"items": []
},
{
"id": 221,
"level": "3",
"text": "MCDog",
"type": "Item",
"items": null
},
{
"id": 222,
"level": "3",
"text": "MCCat",
"type": "Item",
"items": null
},
{
"id": 3,
"level": "1",
"text": "Bruce",
"type": "Folder",
"items": []
},
{
"id": 31,
"level": "2",
"text": "BTable",
"type": "Item",
"items": []
},
{
"id": 311,
"level": "3",
"text": "BTDog",
"type": "Item",
"items": null
},
{
"id": 312,
"level": "3",
"text": "BTCat",
"type": "Item",
"items": null
},
{
"id": 32,
"level": "2",
"text": "Chair",
"type": "Item",
"items": []
},
{
"id": 321,
"level": "3",
"text": "BCDog",
"type": "Item",
"items": null
},
{
"id": 322,
"level": "3",
"text": "BCCat",
"type": "Item",
"items": null
}
];
Conditions:
Object have unknowns level. Some child item may have one level down and some could have up to 5.
Questions
The fd function in the code is what I have come up with. I believe there's a 'cleaner' way to do this, just can't think of something. Plus, the function return items object, render it circular object.
JsBin:
http://jsbin.com/debojiqove/2/edit?html,js,output
Is there a way to flatten object recursively with lodash or just plain JavaScript?.
A solution in plain Javascript with respect to the items. It does not mutate the source array.
function flat(r, a) {
var b = {};
Object.keys(a).forEach(function (k) {
if (k !== 'items') {
b[k] = a[k];
}
});
r.push(b);
if (Array.isArray(a.items)) {
b.items = a.items.map(function (a) { return a.id; });
return a.items.reduce(flat, r);
}
return r;
}
var data = [{ "id": 1, "level": "1", "text": "Sammy", "type": "Item", "items": [{ "id": 11, "level": "2", "text": "Table", "type": "Item", "items": [{ "id": 111, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 112, "level": "3", "text": "Cat", "type": "Item", "items": null }] }, { "id": 12, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 121, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 122, "level": "3", "text": "Cat", "type": "Item", "items": null }] }] }, { "id": 2, "level": "1", "text": "Sundy", "type": "Item", "items": [{ "id": 21, "level": "2", "text": "MTable", "type": "Item", "items": [{ "id": 211, "level": "3", "text": "MTDog", "type": "Item", "items": null }, { "id": 212, "level": "3", "text": "MTCat", "type": "Item", "items": null }] }, { "id": 22, "level": "2", "text": "MChair", "type": "Item", "items": [{ "id": 221, "level": "3", "text": "MCDog", "type": "Item", "items": null }, { "id": 222, "level": "3", "text": "MCCat", "type": "Item", "items": null }] }] }, { "id": 3, "level": "1", "text": "Bruce", "type": "Folder", "items": [{ "id": 31, "level": "2", "text": "BTable", "type": "Item", "items": [{ "id": 311, "level": "3", "text": "BTDog", "type": "Item", "items": null }, { "id": 312, "level": "3", "text": "BTCat", "type": "Item", "items": null }] }, { "id": 32, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 321, "level": "3", "text": "BCDog", "type": "Item", "items": null }, { "id": 322, "level": "3", "text": "BCCat", "type": "Item", "items": null }] }] }];
document.write('<pre>' + JSON.stringify(data.reduce(flat, []), 0, 4) + '</pre>');
With a bit of ES6 flavor
function flatten(xs) {
return xs.reduce((acc, x) => {
acc = acc.concat(x);
if (x.items) {
acc = acc.concat(flatten(x.items));
x.items = [];
}
return acc;
}, []);
}
Using _.flatMapDeep (available since Lodash 4.7):
var flatten = function(item) {
return [item, _.flatMapDeep(item.items, flatten)];
}
var result = _.flatMapDeep(data, flatten);
A shorter solution using reduce and recursion
function flatten(data){
return data.reduce(function(result,next){
result.push(next);
if(next.items){
result = result.concat(flatten(next.items));
next.items = [];
}
return result;
},[]);
}
var data = [
{
"id": 1,
"level": "1",
"text": "Sammy",
"type": "Item",
"items": [
{
"id": 11,
"level": "2",
"text": "Table",
"type": "Item",
"items": [
{
"id": 111,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 112,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
}
]
},
{
"id": 12,
"level": "2",
"text": "Chair",
"type": "Item",
"items": [
{
"id": 121,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 122,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
}
]
}
]
},
{
"id": 2,
"level": "1",
"text": "Sundy",
"type": "Item",
"items": [
{
"id": 21,
"level": "2",
"text": "MTable",
"type": "Item",
"items": [
{
"id": 211,
"level": "3",
"text": "MTDog",
"type": "Item",
"items": null
},
{
"id": 212,
"level": "3",
"text": "MTCat",
"type": "Item",
"items": null
}
]
},
{
"id": 22,
"level": "2",
"text": "MChair",
"type": "Item",
"items": [
{
"id": 221,
"level": "3",
"text": "MCDog",
"type": "Item",
"items": null
},
{
"id": 222,
"level": "3",
"text": "MCCat",
"type": "Item",
"items": null
}
]
}
]
},
{
"id": 3,
"level": "1",
"text": "Bruce",
"type": "Folder",
"items": [
{
"id": 31,
"level": "2",
"text": "BTable",
"type": "Item",
"items": [
{
"id": 311,
"level": "3",
"text": "BTDog",
"type": "Item",
"items": null
},
{
"id": 312,
"level": "3",
"text": "BTCat",
"type": "Item",
"items": null
}
]
},
{
"id": 32,
"level": "2",
"text": "Chair",
"type": "Item",
"items": [
{
"id": 321,
"level": "3",
"text": "BCDog",
"type": "Item",
"items": null
},
{
"id": 322,
"level": "3",
"text": "BCCat",
"type": "Item",
"items": null
}
]
}
]
}
];
var result = flatten(data);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Plain JavaScript
var data = [{ "id": 1, "level": "1", "text": "Sammy", "type": "Item", "items": [{ "id": 11, "level": "2", "text": "Table", "type": "Item", "items": [{ "id": 111, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 112, "level": "3", "text": "Cat", "type": "Item", "items": null }] }, { "id": 12, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 121, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 122, "level": "3", "text": "Cat", "type": "Item", "items": null }] }] }, { "id": 2, "level": "1", "text": "Sundy", "type": "Item", "items": [{ "id": 21, "level": "2", "text": "MTable", "type": "Item", "items": [{ "id": 211, "level": "3", "text": "MTDog", "type": "Item", "items": null }, { "id": 212, "level": "3", "text": "MTCat", "type": "Item", "items": null }] }, { "id": 22, "level": "2", "text": "MChair", "type": "Item", "items": [{ "id": 221, "level": "3", "text": "MCDog", "type": "Item", "items": null }, { "id": 222, "level": "3", "text": "MCCat", "type": "Item", "items": null }] }] }, { "id": 3, "level": "1", "text": "Bruce", "type": "Folder", "items": [{ "id": 31, "level": "2", "text": "BTable", "type": "Item", "items": [{ "id": 311, "level": "3", "text": "BTDog", "type": "Item", "items": null }, { "id": 312, "level": "3", "text": "BTCat", "type": "Item", "items": null }] }, { "id": 32, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 321, "level": "3", "text": "BCDog", "type": "Item", "items": null }, { "id": 322, "level": "3", "text": "BCCat", "type": "Item", "items": null }] }] }];
var r = [];
function flatten(a) {
if (a.length == 0) return;
var o = {};
o.id = a[0].id;
o.level = a[0].level;
o.text = a[0].text;
o.type = a[0].type
o.items = a[0].items == null ? null : []
r.push(o);
if (Array.isArray(a[0].items)) {
flatten(a[0].items);
}
a.shift();
flatten(a);
}
flatten(data);
document.write('<pre>' + JSON.stringify(r, 0, 2) + '</pre>');
Here is solution using recursive function which I called flattenNestedObjectsArray()(for native JavaScript):
function flattenNestedObjectsArray(arr, part){
var flattened = part || [], items;
arr.forEach(function(v){
if (Array.isArray(v.items) && v.items.length) {
items = v.items;
v.items = [];
flattened.push(v);
flattened.concat(flattened, flattenNestedObjectsArray(items, flattened));
} else {
flattened.push(v);
}
});
return flattened;
}
var flattened = flattenNestedObjectsArray(data);
console.log(JSON.stringify(flattened, 0, 4));
The console.log output:
[
{
"id": 1,
"level": "1",
"text": "Sammy",
"type": "Item",
"items": []
},
{
"id": 11,
"level": "2",
"text": "Table",
"type": "Item",
"items": []
},
{
"id": 111,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 112,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
},
{
"id": 12,
"level": "2",
"text": "Chair",
"type": "Item",
"items": []
},
{
"id": 121,
"level": "3",
"text": "Dog",
"type": "Item",
"items": null
},
{
"id": 122,
"level": "3",
"text": "Cat",
"type": "Item",
"items": null
},
{
"id": 2,
"level": "1",
"text": "Sundy",
"type": "Item",
"items": []
},
{
"id": 21,
"level": "2",
"text": "MTable",
"type": "Item",
"items": []
},
{
"id": 211,
"level": "3",
"text": "MTDog",
"type": "Item",
"items": null
},
{
"id": 212,
"level": "3",
"text": "MTCat",
"type": "Item",
"items": null
},
{
"id": 22,
"level": "2",
"text": "MChair",
"type": "Item",
"items": []
},
{
"id": 221,
"level": "3",
"text": "MCDog",
"type": "Item",
"items": null
},
{
"id": 222,
"level": "3",
"text": "MCCat",
"type": "Item",
"items": null
},
{
"id": 3,
"level": "1",
"text": "Bruce",
"type": "Folder",
"items": []
},
{
"id": 31,
"level": "2",
"text": "BTable",
"type": "Item",
"items": []
},
{
"id": 311,
"level": "3",
"text": "BTDog",
"type": "Item",
"items": null
},
{
"id": 312,
"level": "3",
"text": "BTCat",
"type": "Item",
"items": null
},
{
"id": 32,
"level": "2",
"text": "Chair",
"type": "Item",
"items": []
},
{
"id": 321,
"level": "3",
"text": "BCDog",
"type": "Item",
"items": null
},
{
"id": 322,
"level": "3",
"text": "BCCat",
"type": "Item",
"items": null
}
]
I needed to do the same thing, and while solving my issue found a solution to yours using lodash:
function kids(node) {
return node.items
? [{...node, items: []}, _.map(node.items, kids)]
: {...node, items: null};
}
_.flatMapDeep(data, kids);
Here is my version of the recursive flattenItems function.
Note that I have removed the items property at all levels in the final result.
function flattenItems(data) {
// flat is the array that we will return by the end
var flat = [];
data.forEach(function(item) {
// get child properties only
var flatItem = {};
Object.keys(item).forEach(function(key) {
if(item[key] && item.hasOwnProperty(key) && !Array.isArray(item[key])) {
flatItem[key] = item[key];
}
// recursive flattern on subitems
// add recursive call results to the
// current stack version of "flat", by merging arrays
else if(Array.isArray(item[key])) {
Array.prototype.push.apply(flat, flattenItems(item[key]));
}
});
flat.push(flatItem);
});
// sort by level before returning
return flat.sort(function(i1, i2) {
return parseInt(i1.level) - parseInt(i2.level);
});
}
Here is a fiddle using your sample data, check the console.
Only a single liner function can do this job.
var data = [{ "id": 1, "level": "1", "text": "Sammy", "type": "Item", "items": [{ "id": 11, "level": "2", "text": "Table", "type": "Item", "items": [{ "id": 111, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 112, "level": "3", "text": "Cat", "type": "Item", "items": null }] }, { "id": 12, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 121, "level": "3", "text": "Dog", "type": "Item", "items": null }, { "id": 122, "level": "3", "text": "Cat", "type": "Item", "items": null }] }] }, { "id": 2, "level": "1", "text": "Sundy", "type": "Item", "items": [{ "id": 21, "level": "2", "text": "MTable", "type": "Item", "items": [{ "id": 211, "level": "3", "text": "MTDog", "type": "Item", "items": null }, { "id": 212, "level": "3", "text": "MTCat", "type": "Item", "items": null }] }, { "id": 22, "level": "2", "text": "MChair", "type": "Item", "items": [{ "id": 221, "level": "3", "text": "MCDog", "type": "Item", "items": null }, { "id": 222, "level": "3", "text": "MCCat", "type": "Item", "items": null }] }] }, { "id": 3, "level": "1", "text": "Bruce", "type": "Folder", "items": [{ "id": 31, "level": "2", "text": "BTable", "type": "Item", "items": [{ "id": 311, "level": "3", "text": "BTDog", "type": "Item", "items": null }, { "id": 312, "level": "3", "text": "BTCat", "type": "Item", "items": null }] }, { "id": 32, "level": "2", "text": "Chair", "type": "Item", "items": [{ "id": 321, "level": "3", "text": "BCDog", "type": "Item", "items": null }, { "id": 322, "level": "3", "text": "BCCat", "type": "Item", "items": null }] }] }],
flatIron = (a,b) => a.reduce((p,c) => {!!c.items ? (p.push(c), flatIron(c.items,p), c.items = []) : p.push(c); return p},b),
flatArr = flatIron(data,[]);
document.write('<pre>' + JSON.stringify(flatArr, 0, 2) + '</pre>');
another way with recursive reducer function
_.reduce(data, function reducer(result, val) {
var items = _.reduce(val.items, reducer, []);
val.items = _.isArray(val.items) ? [] : val.items;
return _.concat(result, val, items);
}, []);
Modified Роман Парадеев answer to make it somewhat more dynamic.
function flatten(xs, childSelector) {
return xs.reduce((acc, x) => {
acc = acc.concat(x);
let children = childSelector(x);
if (children) {
acc = acc.concat(flatten(children, childSelector));
}
return acc;
}, []);
}
Now items is not hardcoded, and you can use it flatten(data, x => x.items).
Since Lo-Dash 3.0.0, _.flattenDeep(data) will return a deeply flattened array as you desire. There is also a _.flatten(data) function that flattens shallowly.
Since this older question has been brought back up, here is a modern version. It does not mutate (#Nina Scholz: or mutilate!) the original data, but returns a new array containing new objects.
const flattenItems = (xs) =>
xs. flatMap (({items, ... node}) => [node, ... flattenItems (items || [])])
const data = [{id: 1, level: "1", text: "Sammy", type: "Item", items: [{id: 11, level: "2", text: "Table", type: "Item", items: [{id: 111, level: "3", text: "Dog", type: "Item", items: null}, {id: 112, level: "3", text: "Cat", type: "Item", items: null}]}, {id: 12, level: "2", text: "Chair", type: "Item", items: [{id: 121, level: "3", text: "Dog", type: "Item", items: null}, {id: 122, level: "3", text: "Cat", type: "Item", items: null}]}]}, {id: 2, level: "1", text: "Sundy", type: "Item", items: [{id: 21, level: "2", text: "MTable", type: "Item", items: [{id: 211, level: "3", text: "MTDog", type: "Item", items: null}, {id: 212, level: "3", text: "MTCat", type: "Item", items: null}]}, {id: 22, level: "2", text: "MChair", type: "Item", items: [{id: 221, level: "3", text: "MCDog", type: "Item", items: null}, {id: 222, level: "3", text: "MCCat", type: "Item", items: null}]}]}, {id: 3, level: "1", text: "Bruce", type: "Folder", items: [{id: 31, level: "2", text: "BTable", type: "Item", items: [{id: 311, level: "3", text: "BTDog", type: "Item", items: null}, {id: 312, level: "3", text: "BTCat", type: "Item", items: null}]}, {id: 32, level: "2", text: "Chair", type: "Item", items: [{id: 321, level: "3", text: "BCDog", type: "Item", items: null}, {id: 322, level: "3", text: "BCCat", type: "Item", items: null}]}]}]
console .log (flattenItems (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
This version does not include the fairly useless items property. It would be easy enough to add it in, with something like this:
const flattenItems = (xs) =>
xs. flatMap (({items, ... node}) => [
{... node, items: items == null ? null : []},
... flattenItems (items || [])
])
This solution should work on IE11; uses filter, map, and reduce.
var item = function(x) {
return {
"id": x.id,
"level": x.level,
"text": x.text,
"type": x.type,
"items": x.items ? [] : null
}
}
var flatten = function(a, b) {
return a.concat(b);
};
var onlyUnique = function(acc, curr) {
if (acc.length == 0) {
acc.push(curr);
} else {
var search = acc.filter(function(x){return x.id===curr.id;})
if (search.length == 0) {
acc.push(curr);
}
}
return acc;
}
var newData = data.map(function(x) {
return x.items.map(function(xx) {
return xx.items.map(function(xxx) {
return [item(x), item(xx), item(xxx)];
}).reduce(flatten, []);
}).reduce(flatten, [])
}).reduce(flatten, []).reduce(onlyUnique, []);;
console.log(JSON.stringify(newData, null, 2))
Simple with map and reduce :
export function flatten<T>(value: T): T[] {
const out: T[] = [];
if (value.children) {
const children = Object.values(value.children);
out.push(
value,
...children.map(flatten).reduce((acc, curVal) => {
return acc.concat(curVal);
}),
);
} else {
out.push(value);
}
return out;
}
Here is another solution using object-scan. This library is designed around traversing object hierarchies, so gives a lot of flexibility if this isn't exactly the result one needs.
.as-console-wrapper {max-height: 100% !important; top: 0}
<script type="module">
import objectScan from 'https://cdn.jsdelivr.net/npm/object-scan#18.4.0/lib/index.min.js';
const data = [{ id: 1, level: '1', text: 'Sammy', type: 'Item', items: [{ id: 11, level: '2', text: 'Table', type: 'Item', items: [{ id: 111, level: '3', text: 'Dog', type: 'Item', items: null }, { id: 112, level: '3', text: 'Cat', type: 'Item', items: null }] }, { id: 12, level: '2', text: 'Chair', type: 'Item', items: [{ id: 121, level: '3', text: 'Dog', type: 'Item', items: null }, { id: 122, level: '3', text: 'Cat', type: 'Item', items: null }] }] }, { id: 2, level: '1', text: 'Sundy', type: 'Item', items: [{ id: 21, level: '2', text: 'MTable', type: 'Item', items: [{ id: 211, level: '3', text: 'MTDog', type: 'Item', items: null }, { id: 212, level: '3', text: 'MTCat', type: 'Item', items: null }] }, { id: 22, level: '2', text: 'MChair', type: 'Item', items: [{ id: 221, level: '3', text: 'MCDog', type: 'Item', items: null }, { id: 222, level: '3', text: 'MCCat', type: 'Item', items: null }] }] }, { id: 3, level: '1', text: 'Bruce', type: 'Folder', items: [{ id: 31, level: '2', text: 'BTable', type: 'Item', items: [{ id: 311, level: '3', text: 'BTDog', type: 'Item', items: null }, { id: 312, level: '3', text: 'BTCat', type: 'Item', items: null }] }, { id: 32, level: '2', text: 'Chair', type: 'Item', items: [{ id: 321, level: '3', text: 'BCDog', type: 'Item', items: null }, { id: 322, level: '3', text: 'BCCat', type: 'Item', items: null }] }] }];
const fn = objectScan(['[*].**{items[*]}'], {
rtn: ({ value }) => ({ ...value, items: value.items === null ? null : [] }),
afterFn: ({ result }) => result.reverse()
});
const r = fn(data);
console.log(r);
/* => [
{ id: 1, level: '1', text: 'Sammy', type: 'Item', items: [] },
{ id: 11, level: '2', text: 'Table', type: 'Item', items: [] },
{ id: 111, level: '3', text: 'Dog', type: 'Item', items: null },
{ id: 112, level: '3', text: 'Cat', type: 'Item', items: null },
{ id: 12, level: '2', text: 'Chair', type: 'Item', items: [] },
{ id: 121, level: '3', text: 'Dog', type: 'Item', items: null },
{ id: 122, level: '3', text: 'Cat', type: 'Item', items: null },
{ id: 2, level: '1', text: 'Sundy', type: 'Item', items: [] },
{ id: 21, level: '2', text: 'MTable', type: 'Item', items: [] },
{ id: 211, level: '3', text: 'MTDog', type: 'Item', items: null },
{ id: 212, level: '3', text: 'MTCat', type: 'Item', items: null },
{ id: 22, level: '2', text: 'MChair', type: 'Item', items: [] },
{ id: 221, level: '3', text: 'MCDog', type: 'Item', items: null },
{ id: 222, level: '3', text: 'MCCat', type: 'Item', items: null },
{ id: 3, level: '1', text: 'Bruce', type: 'Folder', items: [] },
{ id: 31, level: '2', text: 'BTable', type: 'Item', items: [] },
{ id: 311, level: '3', text: 'BTDog', type: 'Item', items: null },
{ id: 312, level: '3', text: 'BTCat', type: 'Item', items: null },
{ id: 32, level: '2', text: 'Chair', type: 'Item', items: [] },
{ id: 321, level: '3', text: 'BCDog', type: 'Item', items: null },
{ id: 322, level: '3', text: 'BCCat', type: 'Item', items: null }
] */
</script>
Disclaimer: I'm the author of object-scan

Categories

Resources