How can i get value of list every 2 lines and so on to json (JavaScript)

huangapple go评论120阅读模式
英文:

How can i get value of list every 2 lines and so on to json (JavaScript)

问题

const rawList = `*******A\r\n*******B\r\n*******C\r\n*******D`
const dataList = rawList.split('\r\n');
for (i = 0; i < dataList.length; i += 2) {
  var masterlist = JSON.stringify([dataList[i], dataList[i + 1]]);
  console.log(masterlist)
}
英文:

I have a list of names into text file and i need to convert to json every 2 lines .

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const rawList = `*******A\r\n*******B\r\n*******C\r\n*******D`
const dataList = rawList.split(&#39;\r\n&#39;);
for (i = 0; i &lt; dataList.length; i++) {
  var masterlist = JSON.stringify(dataList[i]);
  console.log(masterlist)
}

<!-- end snippet -->

Output :
"*******A"
"*******B"
"*******C"
"*******D"
...

What i need:
["*******A","*******B"]
["*******C","*******D"]
...

答案1

得分: 0

你可以尝试这段代码,它将Output的所有内容存储在名为arr的数组中,并将其分割成大小为2的块,并将这些块存储在chunks数组中。最后,它将chunks数组打印出来。

英文:

let say you store all of Output in an array called arr

const arr = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]

const chunks = []
const chunkSize = 2;
for (let i = 0; i &lt; arr.length; i += chunkSize) {
    const chunk = arr.slice(i, i + chunkSize);
    chunks.push(chunk)
}

console.log(chunks) // [ [&#39;a&#39;, &#39;b&#39;], [&#39;c&#39;, &#39;d&#39;], [&#39;e&#39;, &#39;f&#39;], [&#39;g&#39;] ]

答案2

得分: 0

以下是您要翻译的内容:

"Several issues, you just split and then stringify the result.

Here is a split and a push to new arrays

const rawList = `*******A\r\n*******B\r\n*******C\r\n*******D\r\n*******E`;
const masterList = [];
const dataList = rawList.split('\r\n');
let cnt = 0;
for (let i = 0; i < dataList.length; i++) {
  if (i > 0 && i%2===0) cnt++; // increment the index
  masterList[cnt] ??= []; // create a new array every second element
  masterList[cnt].push(dataList[i]);
}
console.log(JSON.stringify(masterList))

"

英文:

Several issues, you just split and then stringify the result.

Here is a split and a push to new arrays

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const rawList = `*******A\r\n*******B\r\n*******C\r\n*******D\r\n*******E`;
const masterList = [];
const dataList = rawList.split(&#39;\r\n&#39;);
let cnt = 0;
for (let i = 0; i &lt; dataList.length; i++) {
  if (i &gt; 0 &amp;&amp; i%2===0) cnt++; // increment the index
  masterList[cnt] ??= []; // create a new array every second element
  masterList[cnt].push(dataList[i]);
}
console.log(JSON.stringify(masterList))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月15日 14:05:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定