【问题标题】:Javascript: How to Combine & Filter ArraysJavascript:如何组合和过滤数组
【发布时间】:2017-09-10 01:39:40
【问题描述】:

我有 3 个字符串需要转换为数组,从那里我想过滤然后使用 javascript 组合它们,我需要注意我使用的是 Zapier,他们的 javascript 库有点受限,但这就是我到目前为止:

字符串:

var type  = 'bundle, simple, simple';
var name  = 'Product1, Product2, Product3';
var price = '1.99, 2.99, 3.99';

我需要弄清楚如何使用javascript将上面的3个字符串转换为以下数组:

var itemArray = [
        {type:"bundle", info: {name: "Product1", price: "1.99"}},
        {type:"simple", info: {name: "Product2", price: "2.99"}},
        {type:"simple", info: {name: "Product3", price: "3.99"}}];

从那里我希望过滤掉 bundle 产品类型,只传递 simple 产品数组,我正在这样做:

// Using a for loop
var filtered = [];
for (var i = 0; i < itemArray.length; ++i) {
    var item = itemArray[i];
    if (item.type == 'simple') filtered.push(item);
}

return {filtered}; //this returns just the 2 simple product type arrays

所以我的问题是,如何获取我开始使用的这 3 个字符串并使用 javascript 将它们转换为我的 itemArray 格式?

【问题讨论】:

  • 您确定要[simple, {product2, 2.99}] 还是要[simple, product2, 2.99] 和其他数组一样?
  • @PhillipMartin 可能也可以,理想情况下,我希望每个产品名称和价格在其对应的产品类型下
  • 为什么是三个数组?使用对象!即[{type:bundle,name:prod1,price:1.99},{type:simple,name:prod2,price:2.99}]
  • 你可以在这里使用zip,见stackoverflow.com/questions/4856717/…
  • 谢谢大家!我更新了我的问题,使其更加具体,并添加了我正在使用的当前代码。

标签: javascript arrays zapier


【解决方案1】:

首先,通过map 将它们全部组合成一个对象数组,然后通过filter,然后再次将map 组合成您需要的表示形式。比如:

item_type
    .map((type, index) => ({ 
       type, 
       index, 
       name: item_name[index], 
       price: item_price[index]
    }))
    .filter(el => el.type === 'simple')
    .map(el => [el.type, {name: el.name, price: el.price}])

【讨论】:

    【解决方案2】:

    您可以使用mapfilter 的组合来首先组合您拥有的三个数组,然后过滤掉与item_type='bundle' 匹配的数组。

    var item_type  = ['bundle', 'simple', 'simple'],
        item_name  = ['product1', 'product2', 'product3'],
        item_price = [1.99, 2.99, 3.99],
        res = item_type.map(function(v,i) {
            //combine arrays
            return [v, { [item_name[i]]: item_price[i] }]; 
        }).filter(function(o) {
            // only allow items where 'item_type' is not "bundle"
            return o[0] != "bundle";
        });
    
        console.log(JSON.stringify(res, 2, null));

    【讨论】:

    • 修改@Kind 用户使用过滤器代替切片的解决方案
    【解决方案3】:

    您可以过滤列、转置数组并构建所需的内部数组。

    var item_type = ['bundle', 'simple', 'simple'],
        item_name = ['product1', 'product2', 'product3'],
        item_price = [1.99, 2.99, 3.99],
        result = [item_type, item_name, item_price]
            .map((a, _, aa) => a.filter((b, i) => aa[0][i] !== 'bundle'))
            .reduce((r, a, i) => (a.forEach((b, j) => (r[j] = r[j] || [], r[j][i] = b)), r), [])
            .map(a => ({ type: a[0], info: { name: a[1], price: a[2] } }));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案4】:

      是的... JS 缺少Array.prototype.zip() 功能。让我们发明它并相应地解决它。

      Array.prototype.zip = function(...a){
        return this.map((e,i) => [e].concat(a.map(sa => sa[i])));
      };
      
      var itemType  = ["bundle", "simple", "simple"],
          itemName  = ["product1", "product2", "product3"],
          itemPrice = [1.99,2.99,3.99],
          result    = itemType.zip(itemName,itemPrice)
                              .map(sa => [sa[0],{[sa[1]]:sa[2]}])
                              .filter(t => t[0] === "simple");
      console.log(result);

      PS:我已经交换了最后一个 .map().filter() 函数的位置以满足您的要求,但是在 SO 中不鼓励修改问题以改变先前的答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-03
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 2018-02-05
        • 2012-03-01
        • 1970-01-01
        相关资源
        最近更新 更多