代码之家  ›  专栏  ›  技术社区  ›  Ciprian

javascript-在对象中动态创建数组并将其推送到对象中

  •  1
  • Ciprian  · 技术社区  · 8 年前

    如何填充 filters .

    let filters = {};
    

    要使其看起来像这样:

    filters = {
      color: ["Blue", "Black"],
      size: [70, 50]
    };
    

    所以如果我有一个函数:

    function populate(key, value) {
        //if key is color value gets pushed to filters.color
        //if key is size value gets pushed to filters.size
        //if any other key, create new property with new name
    }
    

    因此,这样做将在过滤器中生成一个新的数组:

    populate(material, "plastic");
    

    过滤器如下所示:

    filters = {
      color: ["Blue", "Black"],
      size: [70, 50],
      material: ["plastic"]
    };
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   Hassan Imam Ravi kant    8 年前

    你可以用 in 检查对象中是否存在键。在此基础上,推送对象数组中的值,否则将创建一个具有数组值的新键。

    let filters = {};
    filters = {
      color: ["Blue", "Black"],
      size: [70, 50]
    };
    
    function populate(key, value) {
        //if key is color value gets pushed to filters.color
        //if key is size value gets pushed to filters.size
        //if any other key, create new property with new name
        if(key in filters)
          filters[key].push(value);
        else
          filters[key] = [value];
    }
    populate('material', "plastic");
    console.log(filters);
        2
  •  1
  •   Narendra Jadhav    8 年前

    你可以用 concat 数组if键的方法 filters 对象,否则您将使用新值分配新数组。

    演示

    var filters = {
      color: ["Blue", "Black"],
      size: [70, 50]
    };
    
    function populate(key, value) {
      filters[key] = (filters[key]||[]).concat(value); 
    }
    
    populate('material', "plastic");
    populate('color', "Red");
    populate('size',55);
    console.log(filters)
     .as-console-wrapper {max-height: 100% !important;top: 0;}
        3
  •  1
  •   Asons Oliver Joseph Ash    8 年前

    你可以做一些简单的事情,比如检查钥匙是否存在,然后 推 或 分配 .

    array[key] ? array[key].push(value) : array[key] = [value];
    

    请注意,您需要将键“material”作为字符串传递,我也建议传递数组,以使函数更可重用。

    filters = {
      color: ["Blue", "Black"],
      size: [70, 50]
    };
    
    function populate(a, k, v) {
      a[k] ? a[k].push(v) : a[k] = [v];
    }
    
    populate(filters, "material", "plastic");
    
    console.log(filters)