簡體   English   中英

在我的情況下如何將對象推入數組

[英]How to push objects into array in my case

我試圖將對象推到數組,對象的差異只是一個屬性。

程式碼片段:

var categoryList = ['product1', 'product2', 'product3'...more]
var productlist = [];
var date = new Date();
var year = date.getFullYear();
var nextYear = year++

for (var a = 0; a < categoryList.length; a++) {
    productList.push({
        date: year + '-' + categoryList[a],
        'items': [{
            'quatity': 0 'type': 'new'
        }]
    });

    productList.push({
        date: nextYear + '-' + categoryList[a],
        'items': [{
            'quantity': 0 'type': 'new',
        }]
    });
}

我需要在今年和明年添加對象,但是我不確定是否有更好的方法可以簡化上述代碼。 謝謝您的幫助!

使用當前代碼,您(當前)將以year == 2015nextYear == 2014 我認為您打算這樣做:

var nextYear = year + 1;

您可以重構代碼,以使用將項目添加到產品列表的功能。 (我以為, quatity屬性只是一個錯字,因此唯一的區別是年份。)

function addProduct(year, product) {
  productList.push({
    date: year + '-' + product,
    items: [{
      quantity: 0,
      type: 'new'
    }]
  });
}

for (var a = 0; a < categoryList.length; a++) {
  addProduct(year, categoryList[a]);
  addProduct(nextYear, categoryList[a]);
}

您可以這樣做;

function addProduct(prodDate) {
    productList.push({
        'date':prodDate,
        'items' : [ {
            'quatity' : 0,
            'type' : 'new'
        } ]
    });
}
for (var a=0; a < categoryList.length; a++) {
    addProduct(year + '-' + categoryList[a]);
    addProduct(nextYear + '-' + categoryList[a]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM