Search code examples
javascriptecmascript-6ecmascript-2016

javascript: Inserting Arrays into object one by one


I need to insert the arrays like locations,commodities into an object which is in this case is refdata. I need to insert the array to object one by one ..as i have done in the code below:-

But i am not getting the desired output.Any help will be appreciated.

var refdata = {
    locations: [],
    commodities: []

}

var locations=[
    {
      "symbol": "IND",
      "name": "INDIA"
    }
  ]

 var commodities= [
    {
      "name": "Aluminium",
      "symbol": "AL"
    }
  ]
this.refdata={locations};
this.refdta={commodities};

console.log(this.refdata)


Solution

  • You can just push the 0 elements of refdata and locations

    var refdata = {
      locations: [],
      commodities: []
    
    }
    
    var locations = [{
      "symbol": "IND",
      "name": "INDIA"
    }]
    
    var commodities = [{
      "name": "Aluminium",
      "symbol": "AL"
    }]
    
    
    refdata.locations.push(locations[0]);
    refdata.commodities.push(commodities[0]);
    
    console.log(refdata);


    Or just assign it directly to override the values.

    var refdata = {
      locations: [],
      commodities: []
    
    }
    
    var locations = [{
      "symbol": "IND",
      "name": "INDIA"
    }]
    
    var commodities = [{
      "name": "Aluminium",
      "symbol": "AL"
    }]
    
    
    refdata.locations = locations;
    refdata.commodities = commodities;
    
    console.log(refdata);