Skip to content Skip to sidebar Skip to footer

Adding Elements From One Array To Another

I want to store all the Data into a new array depending on its type. If it is 'store', the data should be stored in the stores[] array, if the type is customer, the data should be

Solution 1:

varCustomerDB = {
  customer: [],    // should be exactly like the type (to make it easier to add)address: [],     // this too (should be adress not adresses)store: [],       // ...add: functioninsertData(allData) {
    allData.forEach(function(d) {
      this[d.type].push(d);
    });
  }
}

forEach will loop through each object in allData array. For each item, this[d.type] will be evaluated to this["customer"] if, for example, the type is customer which is exactly this.customer (the array for customers).

Solution 2:

You can try to run your function outside of customerDB:

varCustomerDB = 
{
  customer:[],
  addresses:[],
  stores:[],
}

var insertData = function(){
  for (var i = 0; i < allData.length; i++)
    //console.log(allData[i]);
      {
          if (allData[i]['type'] == "store")
              {
                  CustomerDB.stores.push(allData[i]);

              }
          elseif (allData[i]['type'] == "customer")
              {
                  CustomerDB.customer.push(allData[i]);
              }
          elseif (allData[i]['type'] == "address")
              {
                  CustomerDB.addresses.push(allData[i]);
              }
       }
}(); 

Here a codepen: http://codepen.io/giannidk/pen/egbmRL?editors=0012

Post a Comment for "Adding Elements From One Array To Another"