Oops
Oops

Reputation: 1413

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

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

Upvotes: 0

Views: 679

Answers (3)

Mohammed Amir Ansari
Mohammed Amir Ansari

Reputation: 2411

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

Upvotes: 1

S.Visser
S.Visser

Reputation: 4735

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)

Upvotes: 2

navsi100rom
navsi100rom

Reputation: 31

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}

Upvotes: 1

Related Questions