Constructing object array using dynamic keys in react/Javscript

I tried to contrcut the object based on response coming from API.

my key is assigned this.RootKeyValue and my response is assigned to this.keyResponse

this.RootKeyValue is the key of parent of first object .

In second object based on the DynamicKey value need to create the key and values .

 this.RootKeyValue = "AccountDetails";
          
this.keyResponse = 
[ 
    {ICICI: 2,DynamicKey: "ICICI"},
    {SBI: 1.25,DynamicKey: "SBI"}
    {HDFC: 1.75,DynamicKey: "HDFC"}
]   
 
    
    
how to construct the object like below using above key and response

    Expected resut : 
{ 
   AccountDetails : 
    { ICICI :2 , SBI: 1.25,HDFC: 1.75 } 
}           
    I am new to react please suggest how to construct object using the dynamic key values

5 thoughts on “Constructing object array using dynamic keys in react/Javscript”

  1. You build a dynamic object using square bracket notation

    const obj = { ["SomeDynamicKey"]: someValue }
    

    So in your case you can use reduce to build the object from your array:

    this.RootKeyValue = "AccountDetails";
              
    this.keyResponse = 
    [ 
        {ICICI: 2,DynamicKey: "ICICI"},
        {SBI: 1.25,DynamicKey: "SBI"},
        {HDFC: 1.75,DynamicKey: "HDFC"}
    ]   
    
    const result = {
      [this.RootKeyValue] : this.keyResponse.reduce( (acc,item) => ({
        ...acc, 
        [item.DynamicKey]: item[item.DynamicKey]})
      ,{})
    }
    
    console.log(result)
    Reply
  2. const mappedResults = keyResponse.map(item => {
    
      return {
        [item.DynamicKey]: item[item.DynamicKey]
      }
    
    })
    const result = {
      AccountDetails: mappedResults
    }
    Reply
  3. You can use square brackets to handle this very easily, e.g.

    const key = 'DYNAMIC_KEY';
    const obj = { [key]: 'value' };
    
    const RootKeyValue = "AccountDetails";
    const keyResponse = [ 
        { ICICI: 2,DynamicKey: "ICICI" },
        { SBI: 1.25,DynamicKey: "SBI" },
        { HDFC: 1.75,DynamicKey: "HDFC" }
    ];
    
    const newData = { [RootKeyValue]: {} };
    keyResponse.forEach(item => {
      newData[RootKeyValue][item.DynamicKey] = item[item.DynamicKey];
    })
    
    console.log(newData)
    Reply
  4. As the give array already has the dynamic keys and associate value in same object , you can create your desired object very easily like this.

    let given =   [ 
        {ICICI: 2,DynamicKey: "ICICI"},
        {SBI: 1.25,DynamicKey: "SBI"},
        {HDFC: 1.75,DynamicKey: "HDFC"}
    ] , AccountDetails = {};
    
    
    given.forEach(item => {
      AccountDetails[item.DynamicKey] = item[item.DynamicKey] ? item[item.DynamicKey] : ''; 
    })
    
    console.log(AccountDetails);
    Reply

Leave a Comment