Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get values of all adjacent properties at a specific level

Intro

A function which gets values of all adjacent properties at a specific level. It treats arrays with length of 1 item the same as object on it's own.

Todo: Try implementing feature to skip/ignore values that aren't arrays or objects

Data

let data = {
	rules: [{
		name: 'font-style',
		abbr: 'font',
		modifiers: [{
				name: 'caps',
				props: [Array]
			},
			{
				name: 'heading',
				props: [Array]
			},
			{
				name: 'link',
				props: [Array]
			},
			{
				name: 'text',
				props: [Array]
			}
		]
	}]
}

Examples

getAdjValues(data, 0)

/* returns

[
	{ rules: [ [Object] ] }
]
*/

getAdjValues(data, 1)

/* returns

[
	{
	  name: 'font-style',
	  abbr: 'font',
	  modifiers: [ [Object], [Object], [Object], [Object] ]
	}
]
*/

getAdjValues(data, 2)

/* returns

[
    'font-style',
    'font',
    [
        { name: 'caps', props: '[Array]' },
        { name: 'heading', props: '[Array]' },
        { name: 'link', props: '[Array]' },
        { name: 'text', props: '[Array]' }
    ]
]

*/

getAdjValues(data, 3)

/* returns

[
	{ name: 'caps', props: [ [Object], [Object], [Object], [Object], [Object] ] },
	{ name: 'heading', props: [ [Object], [Object], [Object], [Object] ] },
	{ name: 'link', props: [ [Object], [Object], [Object], [Object] ] },
	{ name: 'text', props: [ [Object], [Object], [Object] ] }
]

*/

function getAdjValues(thing, depth) {
function iterValue(thing, depth, i = -1) {
i++
let targetDepth = depth - 1
_.each(thing, function(value, property) {
let newThing = {}
if (Array.isArray(value)) {
if (value.length === 1) {
newThing = value[0]
value = newThing
}
}
if (i === 0 && targetDepth === -1) {
arr.push({
[property]: value
})
}
if (i === targetDepth) {
console.log(i)
arr.push(value)
}
if (typeof value === 'object') {
return iterValue(value, depth, i)
}
})
}
let arr = []
iterValue(thing, depth)
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.