将元素从一个数组添加到另一个数组

时间:2017-02-11 22:30:15

标签: javascript

我希望根据其类型将所有数据存储到新数组中。如果是“store”,数据应该存储在stores []数组中,如果类型是customer,数据应该存储在customer array等中。我对Javascript很新,所以我不确定是否我正确地存储它。

var allData = [
{type:"store", data:{store_id: 297, name: "Scotiabank - Main Branch", address_id: 1023}},
{type:"store", data:{store_id: 614, name: "Scotiabank - Hamilton", address_id: 1984}},
{type:"customer", data:{customer_id: 26, store_id:297, first_name: "Dave", last_name: "Bennett", email: "dbennett@gmail.com", address_id: 4536, add_date: null}},
{type:"customer", data:{customer_id: 59, store_id:193, first_name: "John", last_name: "Stevens", email: "jstevens22@hotmail.com", address_id: 2473, add_date: null}},
{type:"customer", data:{customer_id: 29, store_id:614, first_name: "Sarah", last_name: "Pym", email: "spym99@hotmail.com", address_id: 1611, add_date: null}},
{type:"address", data:{address_id: 1023, address: "2895 Yonge St.", city:"Toronto", province:"ON", postal_code:"L4C02G"}},
{type:"address", data:{address_id: 1984, address: "3611 Main St. West", city:"Hamilton", province:"ON", postal_code:"R5O8H5"}},
];


var CustomerDB = 
{
    customer:[],
    addresses:[],
    stores:[],

    add:function insertData (allData)
    {
      for (var i = 0; i < allData.length; i++)
          {
              if (type =="store")
                  {
                      stores = allData.slice(i);

                  }
              else if (type == "customer")
                  {
                      customer = allData.slice(i);
                  }
              else if (type == "address")
                  {
                      addresses = allDara.slice(i);
                  }
           }
    }
}

2 个答案:

答案 0 :(得分:4)

var CustomerDB = {
  customer: [],    // should be exactly like the type (to make it easier to add)
  address: [],     // this too (should be adress not adresses)
  store: [],       // ...

  add: function insertData(allData) {
    allData.forEach(function(d) {
      this[d.type].push(d);
    });
  }
}

forEach将遍历allData数组中的每个对象。对于每个项目,this[d.type]将被评估为this["customer"],例如,如果类型为customer,则this.customer(客户数组)。

答案 1 :(得分:0)

您可以尝试在customerDB之外运行您的功能:

On Error Resume Next

这是一个代码:http://codepen.io/giannidk/pen/egbmRL?editors=0012