使用JavaScript在ForEach循环中拆分数组值?

时间:2019-04-19 16:02:23

标签: javascript arrays for-loop foreach

我正在尝试进行forEach循环,并取出每个项目并将其分割为一个字符。在这种情况下,我想在“ ||”处拆分数组项文本。我目前拥有的是:

var array = [
  [
    "featured", ["feat||1", "feat||2", "feat||3"]
  ],
  [
    "new", ["new||1", "new||2", "new||3"]
  ]
];

var taxIDs = [];


array.forEach((i) => {
  if (i[1].length) {
    taxIDs.push(i[1].split("||")[1]);
  }
});

所以我试图取i [1]并将其分割为“ ||”并获得该拆分数组中的第二项,但是这样做会引发错误,并且不确定要实现我所需的最佳方法吗?

编辑(这是我在控制台记录阵列时看到的内容:

(3) [Array(2), Array(2)]
 0: (2) ["featured", Array(3)]
   0: "featured"
   1: (3) ["feat||1", "feat||2", "feat||3"]
 1: (2) ["news", Array(2)]
   0: "news"
   1: (2) ["news||1", "news||2", "news||3"]

因此该数组中共有3个级别的数组。

3 个答案:

答案 0 :(得分:1)

这里,您可以使用Array.reduce()destructuring嵌套数组的一种方法。

var array = [
  [
    "featured", ["feat||1", "feat||2", "feat||3"]
  ],
  [
    "new", ["new||1", "new||2", "new||3"]
  ]
];

var taxIDs = array.reduce(
    (acc, [str, arr]) => [...acc, arr.map(str => +str.split("||")[1])], 
    []
);

console.log("taxIDs is: ", taxIDs);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

您也可以将.map()替换为在字符串上使用match()的那个字符:

arr.map(str => +str.match(/\d+/)[0])

此外,如果您希望将ids保留为字符串,则可以避免使用unnary plus

arr.map(str => str.split("||")[1])
// OR
arr.map(str => str.match(/\d+/)[0])

答案 1 :(得分:0)

var array = [
  [
    "featured", ["feat||1", "feat||2", "feat||3"]
  ],
  [
    "new", ["new||1", "new||2", "new||3"]
  ]
];

var taxIDs = [];

array.forEach(function(value, index){ value[1].forEach(function(value, index){taxIDs.push(value.split("||")[0])})})

taxID看起来像这样

 ["feat", "feat", "feat", "new", "new", "new"]

或者如果您想要类似的键

taxIDs
(6) ["1", "2", "3", "1", "2", "3"]

然后在循环中进行如下修改

array.forEach(function(value, index){ value[1].forEach(function(value, index){taxIDs.push(value.split("||")[1])})})

根据更新后的数组结构和问题,这将立即为您服务

此forEach循环将为您提供基本知识,以及我的逻辑工作原理

答案 2 :(得分:0)

var array = [
  [
    "featured", ["feat||1", "feat||2", "feat||3"]
  ],
  [
    "new", ["new||1", "new||2", "new||3"]
  ]
];

var taxIDs = [];

array.forEach(item => {
  taxIDs.push(item[1].map(elem => elem.split('||')[1]));
});

console.log(taxIDs);