Consider the following object arrays:
1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}]
2. [{fname:'name', lname:'last name', address:'my address', email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d10043d18101c1411531e1210">[email protected]</a>'}, {...}, {...}]
The goal is to create a function that takes an array and maps their object keys to generic keys like this:
1. [{key1:'1', key2:'somecode', key3:'this is the description'}, {...}, {...}]
2. [{key1:'name', key2:'last name', key3:'my address', key4:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87eafec7e2eae6eeeba9e4e8ea">[email protected]</a>'}, {...}, {...}]
Initially, mapping the keys directly works fine:
let keys: string[] = Object.keys(this.options[0])
this.replacedItems = this.options.map(item => {
return{
key1: item[keys[0]],
key2: item[keys[1]],
key3: item[keys[2]],
}
});
However, attempting a dynamic approach with variable object property numbers leads to undefined results:
let keys: string[] = Object.keys(this.options[0])
this.replacedItems = this.options.map(item => {
let i=0;
keys.forEach(key=>{
let newKey = 'key'+i;
i++
return { newKey: item[key] }
});
});
This setup returns an array of undefined values. What could be causing this issue?