【问题标题】:Javascript: Combining Strings into Array [duplicate]Javascript:将字符串组合成数组[重复]
【发布时间】:2017-09-10 03:38:04
【问题描述】:

我有 3 个字符串需要转换为单个数组,从那里我想过滤掉 type: "bundle"

我需要注意的是,我使用的是 Zapier 的 Javascript 代码,他们的 javascript 库在我可以使用的功能方面有点受限,但这是我目前所拥有的,如果我硬编码 @987654322 @。我只是无法从 3 个给定的字符串创建我的 itemArray

字符串:

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 格式?

【问题讨论】:

  • 这个问题与欺骗目标有何不同?
  • 我打算删除那个骗子,因为我主要编辑了这个问题并且得到了不再相关的答案。抱歉还在学习这里的规则
  • 也许你更关心如何提问,例如我错过了正确的流程,你有什么,你想要什么以及你尝试过什么。数据结构发生了变化,过滤并没有很好地显示,现在,您拒绝选择作为解决方案一部分的答案。但 morping 问题让回答变得困难。
  • 我同意,应该花更多时间来正确地提出我的问题。以后我会更加小心!感谢您的意见

标签: javascript arrays zapier


【解决方案1】:

首先将字符串变成你想要的三个字符串的数组。然后在 for 循环中,您可以将它们全部推送为您想要的任何(相同)格式,因为所有 3 个列表每个都有 3 个元素。然后您可以使用过滤器功能轻松过滤掉捆绑元素,如下所示。 下面的sn -p会打印出item数组和你请求的过滤值

var types  = 'bundle, simple, simple'.split(", ");
var names  = 'Product1, Product2, Product3'.split(", ");
var prices = '1.99, 2.99, 3.99'.split(", ");
var itemArray = [];
for(var i = 0; i < 3; i++){
    itemArray.push({"type": types[i], "info":{"name": names[i], "price": prices[i]}}); 
}
console.log(itemArray);

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

console.log({filtered});

【讨论】:

  • 这正是我想要的,完美运行——谢谢!
【解决方案2】:

var type  = 'bundle, simple, simple'.split(', '),          // split the
    nameArr  = 'Product1, Product2, Product3'.split(', '), // strings to 
    priceArr = '1.99, 2.99, 3.99'.split(', '),             // get the arrays
    
    res = type.map((v,i) => Object.assign({}, {type: v, info: {name: nameArr[i], price: priceArr[i]}})), //map the objects with specified keys and values from given arrays
    result = res.filter(v => v.type != 'bundle'); //remove the `bundle` type elements
    
    console.log(result);

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 2016-06-18
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    相关资源
    最近更新 更多