首页 > 解决方案 > 拆分数组内部的字符串,然后将其从内部数组中取出,成为外部数组的一项

问题描述

从这里:(这个数组是调用响应)

 [
    { "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"]
...

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

标签: javascriptarraysangularecmascript-6

解决方案


您可以使用map()并返回具有DAY属性和拆分STREAMNAME属性的新数组。您应该使用扩展运算符使数组变平。

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)


推荐阅读