js把循环获取到的数据分段生成几组数组?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js把循环获取到的数据分段生成几组数组?相关的知识,希望对你有一定的参考价值。

比如说我循环从后台读取数据
//这是后台数据
dev_1 : 0:0:1920:1080
separate :
dev_1 : 1133:804:697:276
dev_3 : 1133:0:697:380
separate :
dev_1 : 0:0:1920:1080
separate :
dev_0 : 990:515:929:564
dev_1 : 0:515:990:564
dev_2 : 990:0:929:515
separate :
//js
if ($.trim(array[i]).indexOf("dev") >= 0)
dev_id="dev_"+$.trim(array[i].split("_")[1]);
console.log("id屏幕id,value屏幕开窗信息:" + dev_id);

我想获取到再把他组成数组,但数组大概是这样循环生成的
var artr1=……
var artr2=……
var artr3=["dev_1 ":" 0:0:1920:1080"]
var artr4=["dev_0 ":" 990:515:929:564",
"dev_1 ":" 0:515:990:564",
"dev_2 ":" 990:0:929:515"];
或者这样也行:
var artr1=……
var artr2=……
var artr3="dev_1 : 0:0:1920:1080\r\n;
var artr4="dev_0 : 990:515:929:564\r\ndev_1 : 0:515:990:564\r\ndev_2 :
990:0:929:515\r\n";
最主要是按separate把他们分开组成一组字符,因为我的for循环是一条一条去读取的,我要点想不到用什么方法组成他们了

先定义两个数组变量

var dev = new Array();

var sep = new Array();

if ($.trim(array[i]).indexOf("dev") >= 0) 

var dev_id="dev_"+$.trim(array[i].split("_")[1]);

console.log("id屏幕id,value屏幕开窗信息:" + dev_id);

dev.push(dev_id);

if ($.trim(array[i]).indexOf("separate") >= 0) 

var separate_id=,,,,这里是取出你想要的当前数值.....

sep.push(separate_id);

最后,,处理dev,,sep,,这两个数组数据就好了.....


回答里也扔一个,我自己都看不到追答了

var dev = new Array();

var sep = new Array();

for (var i = 0; i < array[i].length; i++) //从后台数据中,按你自己的分割方法取得的数组

var tmp = new Array(); //设置一个临时变量

var dev_id = "";

var separate_id = "";

if (i == 0) //取第一个dev

if ($.trim(array[i]).indexOf("dev") >= 0)

dev_id = "dev_" + $.trim(array[i].split("_")[1]);

tmp.push(dev_id)

else if ($.trim(array[i]).indexOf("separate") >= 0)

//找到 separate 说明 dev已经取尽

if (i - 1 > 0) //保证不会取得已经压入的第一条dev 

if ($.trim(array[i - 1]).indexOf("dev") >= 0)

dev_id = "dev_" + $.trim(array[i-1].split("_")[1]);

tmp.push(dev_id)

if ($.trim(array[i]).indexOf("separate") >= 0)

separate_id = ""; //这里是取出你想要的当前数值.....

sep.push(separate_id);


dev.push(tmp);

追答

好吧,答到一半,,浏览器挂了..数组成员,,可以是数组形式的..

你是不是想要 

var dev = new Array();

dev的数据形式 [["dev_1 : 0:0:1920:1080"],["dev_1 : 1133:804:697:276","dev_3 : 1133:0:697:380"],["dev_0 : 990:515:929:564","dev_1 : 0:515:990:564","dev_2 : 990:0:929:515"],.............................]

那需要在你的数据处理循环中,var tmpArr = new Array();

将每一组数据中循环后,先压入临时数组,,,,再处理过一组数据后,压入dev,,,这样就能够得到相对规整的数据了...不能动态增加变量的...


参考技术A var arr="dev_1 : 0:0:1920:1080\r\nseparate :\r\ndev_1 : 1133:804:697:276\r\ndev_3 : 1133:0:697:380\r\nseparate :\r\ndev_1 : 0:0:1920:1080\r\nseparate :\r\ndev_0 : 990:515:929:564\r\ndev_1 : 0:515:990:564\r\ndev_2 : 990:0:929:515\r\nseparate :\r\n";
var artr=arr.split("\r\nseparate :\r\n").map(e=>e.split("\r\n").map(ee=>
var s=ee.split(" : ");
if(s.length==2)return [s[0]]:s[1];
).filter(e=>e)).filter(e=>e.length);
console.log(artr);本回答被提问者和网友采纳
参考技术B str.split(/separate\s?:\s?/)

循环遍历多维数组以生成新数据并在节点 js / javascript 中追加新的键值

【中文标题】循环遍历多维数组以生成新数据并在节点 js / javascript 中追加新的键值【英文标题】:Loop over multidimensional array to generate new data and append new key values in node js / javascript 【发布时间】:2020-05-04 22:27:55 【问题描述】:

我有一个这样的对象数组:

var finalresult = [
    "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
    "data": [
            "intent": "delivery",
            "result": [
                "heading": "Delivered",
            ]
        ,
        
            "intent": "orders",
            "result": [
                "heading": "What is the order status"
            ]
        ,
        
            "intent": "orders",
            "result": [
                "heading":"Where is my order"
            ]
        
    ]
,
    "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
    "data": [
            "intent": "feedback",
            "result": [
                "heading": "Hello",
            ]
        ,
        
            "intent": "feedback",
            "result": [
                "heading": "You are good"
            ]
        ,
        
            "intent": "picnic",
            "result": [
                "heading":"Lets go on picnic"
            ]
         ,
        
            "intent": "picnic",
            "result": [
                "heading":"Are you coming for the picnic?"
            ]
         ,
        
            "intent": "order",
            "result": [
                "heading":"When should I pick my order"
            ]
        
    ]
]

这是我期望的最终输出:

[
    "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "delivery,orders",
    "html" : "<h1>Delivered</h1><h1>What is the order status</h1><h1>Where is my order</h1>"
,
    "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "feedback,picnic,order",
    "html" : "<h1>Hello</h1><h1>You are good</h1><h1>Lets go on picnic</h1><h1>Are you coming for the picnic?</h1><h1>When should I pick my order</h1>"
]

这是我迄今为止尝试过的:

    var chatstring = "";
    var final = [];
    keywordset = new Set();
    // console.log(JSON.stringify(finalresult))
    for (i = 0; i < finalresult.length; i++) 
        ////chatarr +="<div class='collapsible'></div>";
        for (j = 0; j < finalresult[i].data.length; j++) 
            //console.log(finalresult[c].data)
            keywordset.add(finalresult[i].data[j].intent);
            // console.log(summary);
            generatehtml(finalresult[j].data)
            nloop++;
            if (nloop == (finalresult.length)) 

               final.push(chatstring)
            
        

        //forEach
    

    function generatehtml(data) 
    return new Promise((resolve, reject) => 
        for (s = 0; s < data.length; s++) 

            for (t = 0; t < data[s].result.length; t++) 
                var response = data[s].result[t].heading;
                  var html = "<div" + response + "</div>";
                  chatstring += html;
            

        

    )

我正在使用一个集合来存储唯一的意图值。我正在使用generatehtml() 函数循环数据并生成html。

预期输出:

"chat": [
    "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "delivery,orders",
    "html" : "<h1>Delivered</h1><h1>What is the order status</h1><h1>Where is my order</h1>"
,
    "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
    "keywords" : "feedback,picnic,order",
    "html" : "<h1>Hello</h1><h1>You are good</h1><h1>Lets go on picnic</h1><h1>Are you coming for the picnic?</h1><h1>When should I pick my order</h1>"
]

我无法弄清楚如何从生成的数据中生成预期的输出数组。 我该怎么做?

【问题讨论】:

【参考方案1】:

您可以使用.map() 遍历输入数组并将每个对象转换为所需的格式:

const data = [
  "Date":"WedJan15202000:00:00GMT+0530(IndiaStandardTime)",
  "data":["intent":"delivery","result":["heading":"Delivered",],"intent":"orders","result":["heading":"Whatistheorderstatus"],"intent":"orders","result":["heading":"Whereismyorder"]]
  , 
  "Date":"WedJan17202000:00:00GMT+0530(IndiaStandardTime)",
  "data":["intent":"feedback","result":["heading":"Hello",],"intent":"feedback","result":["heading":"Youaregood"],"intent":"picnic","result":["heading":"Letsgoonpicnic"],"intent":"picnic","result":["heading":"Areyoucomingforthepicnic?"],"intent":"order","result":["heading":"WhenshouldIpickmyorder"]]
];

const result = data.map(o => (
  Date: o.Date,
  keywords: [...new Set(o.data.map(( intent ) => intent))],
  html: `<h1>$[].concat(...o.data.map(( result ) => result))
                                  .map(( heading ) => heading)
                                  .join("</h1>")</h1>`
));

console.log(result);

【讨论】:

【参考方案2】:

这是您可能会做的事情。

您可以使用以下代码 sn-p 简化您的 for 循环

finalresult.forEach((val) => 
  const output = ;
  output['Date'] = val.Date;
  const intents = [];
  const htmls = [];
  val.data.forEach((obj) => 
    intents.push(obj.intent);
    htmls.push(`<h1>$obj.result[0].heading</h1>`)
  );
  output.keywords = intents.join(',');
  output.html = htmls.join('');
  result.push(output);
);

var finalresult = [
  "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)",
  "data": [
      "intent": "delivery",
      "result": [
        "heading": "Delivered",
      ]
    ,
    
      "intent": "orders",
      "result": [
        "heading": "What is the order status"
      ]
    ,
    
      "intent": "orders",
      "result": [
        "heading": "Where is my order"
      ]
    
  ]
, 
  "Date": "Wed Jan 17 2020 00:00:00 GMT+0530 (India Standard Time)",
  "data": [
      "intent": "feedback",
      "result": [
        "heading": "Hello",
      ]
    ,
    
      "intent": "feedback",
      "result": [
        "heading": "You are good"
      ]
    ,
    
      "intent": "picnic",
      "result": [
        "heading": "Lets go on picnic"
      ]
    ,
    
      "intent": "picnic",
      "result": [
        "heading": "Are you coming for the picnic?"
      ]
    ,
    
      "intent": "order",
      "result": [
        "heading": "When should I pick my order"
      ]
    
  ]
];


const result = [];
finalresult.forEach((val) => 
  const output = ;
  output['Date'] = val.Date;
  const intents = [];
  const htmls = [];
  val.data.forEach((obj) => 
    intents.push(obj.intent);
    htmls.push(`<h1>$obj.result[0].heading</h1>`)
  );
  output.keywords = intents.join(',');
  output.html = htmls.join('');
  result.push(output);
);

console.log(result);

【讨论】:

【参考方案3】:

有很多方法可以做到这一点,其他用户也证明了这一点。

还有一个,使用.map() 迭代您的第一个数组,然后使用.reduce() 使用keywordshtml 构建对象,然后将destructed 放入您的初始数组。

我还在每个步骤中包含了 cmets,以便您更轻松。

finalresult.map(result => ( // this will be our final object
  Date: result.Date,
  ...result.data.reduce((accumulator, current) =>  // looping through our data
    if (!accumulator.keywords.includes(current.intent))  // if intent not already in our keywords
       if (accumulator.keywords.length) accumulator.keywords += ','; // if keywords has at least one, add `,`
       accumulator.keywords += current.intent; // add our new keyword
    

    /** on the next line we map result in case 
     *  array has more than 1 object. We build the 
     *  string we need and while map will return 
     *  an array we use join (with empty string as separator) 
     *  to create a string from our array
     **/
    accumulator.html += current.result.map(res => `<h1>$res.heading</h1>`).join(''); 

    return accumulator;
  ,  // our initial object, that will be filled be reduce and the destructed into our upper object
    keywords: "",
    html: ""
  
)
))

编辑:查看 OP 的 cmets 后,由于可能会获得不同的密钥而不是 heading,因此构建正确输出的函数/解析器会更干净。

接下来还会覆盖同一个对象下的多个key。

function myhtmlparser (res) 
  const html = [];

  Object.keys(res).forEach(key => 
    switch (key) 
      case 'heading':
        html.push(`<h1>$res[key]</h1>`);
        break;
      case 'paragraph':
        html.push(`<p>$res[key]</p>`);
        break;
    
  )

  return html.join('');

然后在你的accumulator.html += ...上使用它:

accumulator.html += current.result.map(res => myhtmlparser(res)).join(''); 

【讨论】:

如果数据数组中多次出现相同意图,则此解决方案将跳过 html 值。例如,它认为 html 仅用于意图顺序的一次出现 请帮我解决这个问题。您的解决方案正在运行 它给了我 "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)", "keywords" : "delivery,orders", "html" : "

Delivered

What is the order status

" 而不是 "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)", "keywords" : "delivery,orders", "html" : "

Delivered

订单状态是什么

我的订单在哪里

"
而不是 res => &lt;h1&gt;$res.heading&lt;/h1&gt;).join('') 你能告诉我一种方法,以便我可以将数据传递给 generatehtml 函数,然后将该值包含在 accumulator.html 中吗? 因为我的标题也可以是这样的:'[\"type\": \"head\", \"text\": \"This is a heading\",\" type\": \"paragraph\", \"text\": \"This is a para\"]' 我将在 generatehtml 函数中解析并返回 html

以上是关于js把循环获取到的数据分段生成几组数组?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 RegExp 循环遍历字符串并将其分段为数组?

分段错误和神秘的循环行为

来自 for 循环的分段错误

生成器

第三次实验计算分段函数 第四次计算分段函数和循环NEW 第五次分支+循环加强版 实验报告

分段错误:循环打印时为 11