Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var structure = {
- name: 'alpha',
- array: [
- { name: 'beta' },
- { name: 'gamma' }
- ],
- object: {
- name: 'delta',
- array: [
- { name: 'epsilon' }
- ]
- }
- };
- // expected result: [ 'alpha', 'beta', 'gamma', 'delta', 'epsilon' ]
- function getPropertyRecursive(obj, property) {
- var values = [];
- _.each(obj, function(value, key) {
- if (key === property) {
- values.push(value);
- } else if (_.isObject(value)) {
- values = values.concat(getPropertyRecursive(value, property));
- }
- });
- return values;
- }
- _.mixin({
- toPairsDeep: obj => _.flatMap(
- _.toPairs(obj), ([k, v]) =>
- _.isObjectLike(v) ? _.toPairsDeep(v) : [[k, v]])
- });
- result = _(structure)
- .toPairsDeep()
- .map(1)
- .value()
- result = _(structure)
- .toPairsDeep()
- .filter(([k, v]) => k === 'name')
- .map(1)
- .value()
- function walk(o, f) {
- f(o);
- if(typeof o !== 'object') return;
- if(Array.isArray(o)) return o.forEach(e => walk(e, f));
- for(let prop in o) walk(o[prop], f);
- }
- const arr = [];
- walk(structure, x => if(x !== undefined && x.name) arr.push(x.name));
- function walk(o, f, context) {
- f(o, context);
- if(typeof o !== 'object') return context;
- if(Array.isArray(o)) return o.forEach(e => walk(e, f, context)), context;
- for(let prop in o) walk(o[prop], f, context);
- return context;
- }
- const arr = walk(structure, (x, context) => {
- if(x !== undefined && x.name) context.push(x.name);
- }, []);
- _.mixin({
- extractLeaves: (obj, filter, subnode) => {
- var filterKv = _(filter).toPairs().flatMap().value()
- var arr = _.isArray(obj) ? obj : [obj]
- return _.flatMap(arr, (v, k) => {
- if (v[filterKv[0]] === filterKv[1]) {
- var vClone = _.clone(v)
- delete vClone[subnode]
- return vClone
- } else {
- return _.extractLeaves(v[subnode], filter, subnode)
- }
- })
- }
- });
- {
- "name": "raka",
- "type": "dir",
- "children": [{
- "name": "riki",
- "type": "dir",
- "children": [{
- "name": "roko",
- "type": "file"
- }]
- }]
- }
- _.extractLeaves(result, {type: "file"}, "children")
- [
- {
- "name": "roko",
- "type": "file"
- }
- ]
Add Comment
Please, Sign In to add comment