代码之家  ›  专栏  ›  技术社区  ›  brohymn

在数组中拆分一个字符串,然后将其从内部数组中取出,成为外部数组的一个项目

  •  0
  • brohymn  · 技术社区  · 6 年前

    从这里:(这个数组是call response)

     [
        { "DAY": 20190323,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190324,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190325,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190326,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190327,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
     ]
    

    [
         [20190323, "Instant Purification", "Pentatone A/B" , "This is a drill"],
         [20190324, "Instant Purification", "Pentatone A/B" , "This is a drill"],
         [20190325, "Instant Purification", "Pentatone A/B" , "This is a drill"],
         [20190326, "Instant Purification", "Pentatone A/B" , "This is a drill"],
         [20190327, "Instant Purification", "Pentatone A/B" , "This is a drill"]
    ]
    

    所以我做了:

    const yearDays = res.map(x => x['YEAR_DAY']);
    const streams = res.map(x => x['STREAMNAME']);
    
    const labeler = yearDays.map((v, i) => {return [v, String(streams[i]).split(/\s*(?:,|$)\s*/)]; });
    

    [20190323, ["Instant Purification", "Pentatone A/B" , "This is a drill"]
    [20190324, ["Instant Purification", "Pentatone A/B" , "This is a drill"]
    [20190325, ["Instant Purification", "Pentatone A/B" , "This is a drill"]
    ...
    

    如何从内部数组中取出所有元素并使它们成为外部数组的一部分?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Maheer Ali    6 年前

    你可以用 map() 并返回新数组 DAY 财产和分割 STREAMNAME 财产。你应该使用 Spread Operator 使阵列平坦。

    let arr = [
        { "DAY": 20190323,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190324,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190325,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190326,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
        { "DAY": 20190327,"NAME": "BTA130", "STREAMNAME": "Instant Purification, Pentatone  A/B , This is a drill"},
     ]
     
     let res = arr.map(({DAY,STREAMNAME})=>[DAY,...STREAMNAME.split(', ')])
     
     console.log(res)