简体   繁体   中英

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:'my@email.com'}, {...}, {...}]

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:'my@email.com'}, {...}, {...}]

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM