简体   繁体   English

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

[英]Javascript - Create array dynamically in object and push to it

How do I populate filters . 如何填充filters

let filters = {};

To make it look like this: 使它看起来像这样:

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

So if I would have a function: 因此,如果我有一个功能:

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
}

So doing this would result in a new array in filters: 因此,这样做会在过滤器中产生一个新的数组:

populate(material, "plastic");

And filters would look like this: 过滤器如下所示:

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

You can use in to check if the key exists in the object. 您可以使用in检查对象中是否存在密钥。 Based on that push the value in the object array otherwise creates a new key with array value. 基于该推送,否则将在对象数组中创建该值,否则将创建一个具有数组值的新键。

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

You could do something simple as this, where you check if the key exist and then push or assign . 您可以执行以下简单操作:在其中检查密钥是否存在,然后按下分配

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

Do note, you need to pass the key "material" as a string, and I as well recommend to pass the array too, to make the function more reusable. 请注意,您需要将键“ 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) 

You can use concat method of array if key present in filters Object otherwise it you will assign new array with new value. 如果filters对象中存在键,则可以使用数组的concat方法,否则将为新数组分配新值。

DEMO 演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM