英文:
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('\r\n');
for (i = 0; i < 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 = ['a','b','c','d', 'e', 'f', 'g']
const chunks = []
const chunkSize = 2;
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
chunks.push(chunk)
}
console.log(chunks) // [ ['a', 'b'], ['c', 'd'], ['e', 'f'], ['g'] ]
答案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('\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))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论