0

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)
AConsumer
  • 2,461
  • 2
  • 25
  • 33

3 Answers3

0

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);
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

In ES6 you can use a shorthand syntax in this case:

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

let commodities = [{
  "name": "Aluminium",
  "symbol": "AL"
}]

let refdata = { locations, commodities }

console.log(refdata)
let refdata = { locations, commodities }

is short for

let refdata = { locations: locations, commodities: commodities }

If you need to do it one by one, as described in your question, you can use Object.assign():

let refdata = {}

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

refdata = Object.assign(refdata, { locations })

let commodities = [{
  "name": "Aluminium",
  "symbol": "AL"
}]

refdata = Object.assign(refdata, { commodities })

console.log(refdata)

Hint: I'm adding this answer because you tagged your questions .

connexo
  • 53,704
  • 14
  • 91
  • 128
0

As you wanted to insert items one by one into refdata location array. I suppose you wanted to do some manipulation on each item. If so the below code will be appropriate.

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

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

 var commodities= [
    {
      "name": "Aluminium",
      "symbol": "AL"
    }
  ];
  
 for (loc of locations) {
    // Do your object manipulation of loc if required
    console.log(loc);
    refdata.locations.push(loc);
 };
 for (commodity of commodities) {
    // Do your object manipulation of commodity if required
    console.log(commodity);
    refdata.commodities.push(commodity);
 };
 
console.log(refdata);