Home > Net >  How to map through an array and dynamically set key and values inside mapped array in javascript
How to map through an array and dynamically set key and values inside mapped array in javascript

Time:08-25

I have an array arr with the below format

data:{
  result: [Array]
 }

I am mapping an array and setting key and values to form new array like this.

const userData= arr.map((user) => ({
userid : user.data.result[0].info.uid,
termStat: user.data.result[0].info['attr'].termStat

}));

This will give me the userData array as

[{
userid: 'y74',
termStat:[[Object]]
}]

How can I make this to the below format. Placing key as the value of userid. This is the expected result

{
  y74: { termStat: [[Object]]
 }

CodePudding user response:

You can just use the userid as a variable putting it in a square brackets and assing it a value if I understand it correctly

[user.data.result[0].info.uid]: {'termStat': user.data.result[0].info['attr'].termStat}

CodePudding user response:

You can set the key as the userid.

const arr = [{
  data: {
    result: [
    {
      info: {
        uid: 12,
        attr: {
          termStat: 'foobar'
        }
      }
    }
    ]
  }
}]

const userData= arr.map(user => ({
  [user.data.result[0].info.uid]: { 
    'termStat': user.data.result[0].info['attr'].termStat 
  }
}));

console.log(userData)

CodePudding user response:

Array map function always returns an array. If you want to return a map from the input array Array.reduce() function will be helpful. Something like:

const arr = [{ data: { result: [{ info: { uid: 'y74', attr: { termStat: [[{}]] } } }] } }];

const userData = arr.reduce((result, user) => {
    const key = user.data.result[0].info.uid;
    const termStat = user.data.result[0].info['attr'].termStat;
    result[key] = {termStat};
    return result;
}, {});

console.log(userData);

Hope this helps :)

  • Related