I have an array and a sample object like this:
const array = ['a', 'b.c', 'c.d.e']
Sample
const sample = {
'aa': 'test',
'a': 'value',
'b': {
'c': 'value'
},
'c': {
'd': {
'e': 'value'
}
},
'e': {
'f': {
'g': {
'h' : 'value'
}
}
}
}
Then I want to make a new object basing on the sample. The result should look like this:
const newSample = {
'aa': 'test',
'a': 'oldvalue' + 1,
'b': {
'c': 'oldvalue' + 1
},
'c': {
'd': {
'e': 'oldvalue' + 1
}
},
'e': {
'f': {
'g': {
'h' : 'oldvalue'
}
}
}
}
I'm thinking of loop through the array and count the length of each element. However, it's not as efficient as the level of the array and sample increase. Are there any algorithms that can be done better?
const array = ['a', 'b.c', 'c.d.e']
const sample = {
'aa': test,
'a': 'value',
'b': {
'c': 'value'
},
'c': {
'd': {
'e': 'value'
}
},
'e': {
'f': {
'g': {
'h' : 'value'
}
}
}
}
const newSample = {}
const transformer = (array) => {
array.forEach(item => {
const itemArr = item.split('.')
if (itemArr.length === 1) {
console.log(sample[itemArr[0]])
newSample[itemArr[0]] = sample[itemArr[0]] + 1
}
// the condition goes on...
})
}
transformer(array)
console.log(newSample)
Thanks,