代码之家  ›  专栏  ›  技术社区  ›  Keval Mehta

将数据推送到javascript对象中不起作用

  •  -4
  • Keval Mehta  · 技术社区  · 6 年前

    我想把数据推送到Javascript对象中,但是我做不到。

    var obj = {};
    if(cust_opt_title == "Size"){
        obj['Size'] = {'custom_option_select_text': 'Red + $200.00'};
        obj['Size'].push({'custom_option_select_text': 'Red + $200.00'}); // I tried this also
    } else {
        obj['Color'] = {'custom_option_select_text': 'Red + $200.00'};
        obj['Color'].push({'custom_option_select_text': 'Red + $200.00'}); // I tried this also
    }
    

    我想要这样的输出:

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  3
  •   Nina Scholz    6 年前

    如果不存在,则需要在推送值之前创建一个数组。

    Array#push Array .

    var obj = {},
        cust_opt_title = 'Size';
    
    if (cust_opt_title === "Size") {
        obj['Size'] = obj['Size'] || [];
        obj['Size'].push({ custom_option_select_text: 'Red + $200.00' });
    } else {
        obj['Color'] = { custom_option_select_text: 'Red + $200.00' };
    }
    
    console.log(obj);
        2
  •  1
  •   Elmar Beckmann    6 年前

    obj['size']不是一个数组,因此不能推送到它(只能推送到数组)。我看到你想把多个对象推到对象属性中 我想你希望它们是数组,即使它们是空的 将它们定义为数组 第一。

    var obj = {
        'Size': [],
        'Color': []
    };
    
    if(cust_opt_title === "Size"){
        obj['Size'].push({'custom_option_select_text': 'Red + $200.00'});
    } else {
        obj['Color'].push({'custom_option_select_text': 'Red + $200.00'});
    }