javascript 我正在使用whatsapp聊天导出.我把它作为一个Json.我想存储continuos消息作为一个消息在NodeJs

qzwqbdag  于 2023-05-16  发布在  Java
关注(0)|答案(2)|浏览(68)

我有一个whatsapp聊天导出我想使continuos消息作为单一消息
the messages are given below i want to make the continuos messages as single message
My NodeJs code
in this code i read the data from txt file a store in array则连续的消息应该放在一个对象下this program only joins two messages only not join the third onehow do i join the third element in the object`

const fs = require("fs");

var data = JSON.parse(fs.readFileSync("file.txt"));
var newData = [];
data.forEach((x, index, arr) => {
  if (index < arr.length - 1) {
    y = arr[index + 1];
    xkey = Object.keys(x);
    ykey = Object.keys(y);
    //console.log(xkey, ykey);
    if(xkey[0] == ykey[0]) {
      x = { [xkey]: x[xkey] + " " + y[ykey] };
      delete arr[index + 1];
    }
    newData.push(x);
  }
});
console.log(newData);

This is the text file

[
  { itachi: 'Sir' },{ itachi: 'hi ' },{ itachi: 'hello' },
  { Batman: 'hi' },Batman: 'how r u' },{ itachi: 'fine' },
 
]

The Output i got

[
  { itachi: 'Sir || hi' },{ itachi: 'hello' },
    { Batman: 'hi ||how r u' },{ itachi: 'fine' }, 
]

The desired Output

{ itachi: 'Sir || hi ||hello' },  { Batman: 'hi ||how r u' }, { itachi: 'fine' },
]
sr4lhrrt

sr4lhrrt1#

你只需要检查最终值。因为代码index < arr.length - 1跳过了最后一个值

var data = [
  { itachi: 'Sir' },{ itachi: 'hi ' },{ itachi: 'hello' },
  { Batman: 'hi' },{Batman: 'how r u' },{ itachi: 'fine' },
]
var newData = [];
data.forEach((x, index, arr) => {
  if(index < arr.length - 1){
    y = arr[index + 1];
    xkey = Object.keys(x);
    ykey = Object.keys(y);
    //console.log(xkey, ykey);
    if(xkey[0] == ykey[0]) {
      x = { [xkey]: x[xkey] + " " + y[ykey] };
      delete arr[index + 1];
    }
    newData.push(x);
  }else{
    newData.push(x);
  }
});
console.log(newData);
fgw7neuy

fgw7neuy2#

我找到了答案:我将消息存储在下一个元素中,以便它再次检查值:

var data = [
  { itachi: 'Sir' },{ itachi: 'hi ' },{ itachi: 'hello' },
  { Batman: 'hi' },{Batman: 'how r u' },{ itachi: 'fine' },]

data.forEach((x, index, arr) => {
  if(index < arr.length - 1){
    y = arr[index + 1];
    xkey = Object.keys(x);
    ykey = Object.keys(y);
    //console.log(xkey, ykey);
    if(xkey[0] == ykey[0]) {
      x = { [xkey]: x[xkey] + " " + y[ykey] };
     arr[index]=""
     arr[index+1]=x
      
      
    }
    
  }
})
data=data.filter(x=>x!=="")
console.log(data)

相关问题