gothaf
gothaf

Reputation: 228

Map an object array with unknown length and unknown key names

Here are some object arrays:

1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}]

2. [{fname:'name', lname:'last name', address:'my address', email:'[email protected]'}, {...}, {...}]

What I need to do is create a function where I pass an array and map their object keys to generic keys so they become like this:

1. [{key1:'1', key2:'somecode', key3:'this is the description'}, {...}, {...}]

2. [{key1:'name', key2:'last name', key3:'my address', key4:'[email protected]'}, {...}, {...}]

When I do this

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]],
  }
});

it works fine, but since the object's properties number is not fixed, I tried this

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] }
  });
}); 

which rerurns an array of undefined... What am I doing wrong?

Upvotes: 0

Views: 1237

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

Take the second parameter of .map to get the current index you're iterating over, and concatenate it with 'key'. You can also use Object.values instead of Object.keys to get the values immediately (since you're not actually using the original keys):

const options = [{id:'1', code:'somecode', desc:'this is the description'}];
const replacedItems = options.map(obj => Object.fromEntries(
  Object.values(obj).map((val, i) => ['key' + (i + 1), val])
));
console.log(replacedItems);

Upvotes: 3

Related Questions