Javascript - 在对象中动态创建数组并推送到它

时间:2018-05-21 12:02:46

标签: javascript

如何填充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 个答案:

答案 0 :(得分:3)

您可以使用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);

答案 1 :(得分:1)

你可以做一些简单的事情,检查密钥是否存在,然后推送分配

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

请注意,您需要传递密钥"材料"作为一个字符串,我也建议传递数组,以使该函数更可重用。



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)




答案 2 :(得分:1)

如果filters对象中存在键,则可以使用concat数组方法,否则您将为新数组分配新值。

<强>样本

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;}