Create Parent and Child Relationship Using Lodash

Create parent and child relationship using lodash

let parentJSON =[{ index:1, name: 'a'}, {index:2, name: 'b'}, {index:3, name: 'c'}, {index:4, name: 'd'}]
let childJSON =[ { index:1, name: 'aa', parent_index:1}, {index:2, name: 'ab', parent_index:1}, {index:3, name: 'ba', parent_index: 2}, {index:4, name: 'bb', parent_index: 2}, {index:5, name: 'ca', parent_index: 3}, {index:6, name: 'ad', parent_index: 1}]
let answer = [];
parentJSON.forEach(parent => { answer.push(parent); childJSON.forEach(child => { if(child.parent_index === parent.index){ child.found = true; answer.push(child); } })});
console.log(answer)

Nesting a parent child relationship in lodash, given the parent id and children

This is my take on the question (fiddle):

var data = getData();

var group = getTree(data);

console.log(group);

function getTree(flat) {
return _.reduce(flat, function (treeObj, item, prop, flatTree) {
var children = _.map(item.children, function (childId) {
return _.set(flatTree[childId], 'isCategory', true);
}).concat(_.map(item.items, function(item) {
return _.set(item, 'isCategory', false);
}));

item.children = !!children.length ? children : null;

delete item.items;

item.parent === null && (treeObj[prop] = item);

return treeObj;
}, {});
}

nested filter with lodash for parent children relationship

Lodash does not provide a built-in utility to achieve this. You can solve this by recursively traversing throughout your nested collections. Check the solution below, each section of the code is commented.

function getIds(collection, ids) {

// store ids in this variable
var result = [];
// determines if an id is found,
var found = false;

// makes sure that ids is always an array of id
ids = [].concat(ids);

// iterate over the collection, name the callback for recursion
// if you prefer to use lodash, then use:
// _.each(collection, function iterator(value) {...});
collection.forEach(function iterator(value) {
// Matching the list of `ids` from the iterated userId.
// If a match is found, then we set `found` to true.
var isStop = ~ids.indexOf(value.userId) && (found = true);

// did we get a match?
if(found) {
// add the matched ID and the IDs from its descendants
result.push(value.userId);
}

// itereate recursively over its descendants
// If you prefer to use lodash then use:
// _.each(value.children, iterator)
(value.children || []).forEach(iterator);

// is the currently iterated item's ID within the list of `ids`?
if(isStop) {
// set `found` to false, to prevent adding IDs that aren't matched
found = false;
}
});

// return an array of IDs
return result;

}

var data = {  "children": [{    "userId": "1",    "name": "Kevin",    "type": "ROOT",    "active": true,    "children": [{      "userId": "10023872531",      "name": "Selvin",      "type": "USER",      "active": true,      "children": []    }, {      "userId": "10003200835",      "name": "adduser",      "type": "USER",      "active": true,      "children": []    }, {      "userId": "-1111111",      "name": "Merisa",      "type": "USER",      "active": true,      "children": []    }, {      "userId": "10165381976",      "name": "Kam",      "type": "PARENT",      "active": true,      "children": [{        "userId": "10165381977",        "name": "Pam",        "type": "USER",        "active": true,        "children": [{          "userId": "10165381978",          "name": "Ram",          "type": "PARENT",          "active": true,          "children": [{            "userId": "10232392492",            "name": "Sam",            "type": "USER",            "active": true,            "children": []          }]        }]      }]    }]  }]};
function getIds(collection, ids) { // store ids in this variable var result = []; // determines if an id is found, var found = false; // makes sure that ids is always an array of id ids = [].concat(ids); // iterate over the collection, name the callback for recursion // if you prefer to use lodash, then use: // _.each(collection, function iterator(value) {...}); collection.forEach(function iterator(value) { // Matching the list of `ids` from the iterated userId. // If a match is found, then we set `found` to true. var isStop = ~ids.indexOf(value.userId) && (found = true); // did we get a match? if(found) { // add the matched ID and the IDs from its descendants result.push(value.userId); } // itereate recursively over its descendants // If you prefer to use lodash then use: // _.each(value.children, iterator) (value.children || []).forEach(iterator);
// is the currently iterated item's ID within the list of `ids`? if(isStop) { // set `found` to false, to prevent adding IDs that aren't matched found = false; } }); // return an array of IDs return result; }
console.log('ID to find: 10165381978');console.log(getIds(data.children, '10165381978'));
console.log('IDs to find: 10023872531, 10165381976');console.log(getIds(data.children, [ '10023872531', '10165381976']));
.as-console-wrapper {  min-height: 100%;  top: 0;}

transform object to array with parent child relationship in lodash

You can use Object.keys for that:

var obj = {    a: [ {id:1},{id:2},{id:3}],    b: [ {id:4},{id:5},{id:6}],    c: [ {id:7},{id:8},{id:9}]}
var result = Object.keys(obj).map(function(key) { return { title: key, items: obj[key] }})
console.log(result);

Reorder array of objects that contain parent/child relationships with lodash or vanilla js

A single sort does not work, because of the parent children relation, which is not considered while sorting the data.

This solution works in three parts:

  1. Sorts data by alphabet, because the following tree is build in insertion order.

  2. Builds a tree with the given relationship.

  3. Traverses the tree and gets the sorted flat data back.

var data = [{ id: 8, name: 'Shirts', slug: 'shirts', parent_id: null }, { id: 9, name: 'Pants', slug: 'pants', parent_id: null }, { id: 10, name: 'Vintage Prints', slug: 'vintage-prints', parent_id: 8 }, { id: 11, name: 'Cotton Tee', slug: 'cotton-tee', parent_id: 8 }, { id: 12, name: 'Business Khakis', slug: 'business-khakis', parent_id: 9 }]    .sort(function (a, b) {        return a.name.localeCompare(b.name);    }),    tree = function (data, root) {        var r = [], o = {};        data.forEach(function (a) {            o[a.id] = { data: a, children: o[a.id] && o[a.id].children };            if (a.parent_id === root) {                r.push(o[a.id]);            } else {                o[a.parent_id] = o[a.parent_id] || {};                o[a.parent_id].children = o[a.parent_id].children || [];                o[a.parent_id].children.push(o[a.id]);            }        });        return r;    }(data, null),    sorted = tree.reduce(function traverse(r, a) {        return r.concat(a.data, (a.children || []).reduce(traverse, []));    }, [])
console.log(sorted);console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Underscore/Lodash - Object from parent/children

You can iterate over the collection to get the required structure:

// create and indexed object with the _id field as key - improve performance
var indexed = _.indexBy(data, '_id');

// iterate to create the structure
_.each( data, function(datum){
datum.children = [];
if( _.has(datum,'parent')){
indexed[datum.parent].children.push(datum);
}
})

This solution does assume that a parent is processed before each child i.e. the children array is created before it's pushed into. A number of ways to solve if needs be but the above code shows the way to create the nested structure.

Adding object to parent array based on IDs using Lodash

Not sure if I understood correctly what the expected result is, but I gave it a try anyway.

const orderLines = _(data.order.orderLines)
.map(item => {
if (!item.connectedTo) return _.assignIn(item, { addons: [] });

const match = _.find(data.order.orderLines, { id: item.connectedTo });
match.addons = match.addons || [];
match.addons.push(item);

return null;
})
.compact()
.value();

Check the output here: https://codepen.io/andreiho/pen/YEzQRd?editors=0012

Create two level map out of a json map using lodash

After grouping the colors by id, then group by again by color, and map the values of the 2nd grouping to the objects you need:

const colors =  [{"Id":"1","color":"red","size":"10","QTY":"2000","ref":"tr"},{"Id":"1","color":"red","size":"25","QTY":"3000","ref":"tr"},{"Id":"1","color":"blue","size":"15","QTY":"2050","ref":"gt"},{"Id":"2","color":"red","size":"18","QTY":"2010","ref":"tt"}];
const result = _(colors) .groupBy('Id') // group by id .mapValues((values) => _(values) // map the values .groupBy('color') // group by color .mapValues((v) => ({ // map the resulting arrays /* get the id and color from the 1st item in the array */ id: v[0].Id, color: v[0].color, rows: v.map(({ size, QTY }) => ({ // map all elements to row objects size, QTY })) })) .value()) .value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


Related Topics



Leave a reply



Submit