Zipped
by Evgeniy Kvasyuk
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
JavaScript
const values = {
organization: {
name: 'Roga i Kopita'
},
employees: [{
firstName: 'Evgen',
lastName: 'Kvas',
moneys: [{value:1, value2:2}, {value:1, value2:2}]
},
{
firstName: 'Fed',
lastName: 'Mos',
moneys: [{value:1, value2:2}]
}
]
}
const path = 'employees:moneys:value2';
const createWays = (allWays, currentPath, val) => {
let ways = [];
if (allWays.length > 0) {
allWays.forEach(function(path) {
const currentPathVal = _.get(val, `${path}.${currentPath}`);
//if (!currentPathVal) return ways;
ways = Array.isArray(currentPathVal)
? [...ways, ...currentPathVal.map((item, index) => `${path}.${currentPath}[${index}]`)]
: [...ways, ...[`${path}.${currentPath}`]];
});
} else {
const currentPathVal = _.get(val, `${currentPath}`);
//if (!currentPathVal) return ways;
ways = Array.isArray(currentPathVal)
? currentPathVal.map((item, index) => `${currentPath}[${index}]`)
: [`${currentPath}`];
}
return ways;
};
const getZipWays = (path, values) => {
const FIELD_PATH_SEPARATOR = ':';
return path.split(FIELD_PATH_SEPARATOR).reduce((acc, currentPath) => [...createWays(acc, currentPath, values)], []);
};
//getZipWays(path,values);
console.log(getZipWays(path, values));