2021年1月19日星期二

Pushing split JSON back into JSON object

I have a JSON file which can have multiple FromName values. I need to split these into separate values, and push back into the JSON data under FromName (retained the first name) and FromExtra (for the extra name).

I have managed to create the split successfully, however I am unable to get the split to push back into the JSON data in the right place under the right name.

Here is my JSON file:

 [  {      "Name": "News 1",      "FromName": "John Citizen, Jane Doe",      "FromEmail": "testemail@notreal.com"  },  {      "Name": "News 2",      "FromName": "John Citizen",      "FromEmail": "testemail@notreal.com"  },  {      "Name": "News 3",      "FromName": "John Citizen",      "FromEmail": "testemail@notreal.com"  }  

]

Here is the code I have put together so far:

 for (var i = 0; i < abcPre.length; i++) {      if (abcPre.FromName = []) {          var sepNames = (abcPre[i].FromName).split(',');          console.log(sepNames);                      if (sepNames <= [1]) {          var FromExtra = sepNames [1];          console.log(`The new first name ${FromName}`);          console.log(`The second from name ${FromExtra}`);          abcPre[i].push.FromExtra;          console.log(abcPre);          }                    }                   else {          // console.log(`SentDate loop not working`);      }  }  

Closest I have been able to get is to push the information back into the JSON file, but the push is ending up in the wrong place (see below).

[  {      "Name": "News 1",      "FromName": "John Citizen, Jane Doe",      "FromEmail": "testemail@notreal.com"  },  {      "Name": "News 2",      "FromName": "John Citizen",      "FromEmail": "testemail@notreal.com"  },  {      "Name": "News 3",      "FromName": "John Citizen",      "FromEmail": "testemail@notreal.com"  },  {      "John Citizen"  }  

]

This is the output which is what I am trying to achieve:

[  {      "Name": "News 1",      "FromName": "John Citizen",      "FromExtra": "Jane Doe",      "FromEmail": "testemail@notreal.com"  },  {      "Name": "News 2",      "FromName": "John Citizen",      "FromEmail": "testemail@notreal.com"  },  {      "Name": "News 3",      "FromName": "John Citizen",      "FromEmail": "testemail@notreal.com"  }]    

Thank you in advance. Javascript is something I am still learning with.

https://stackoverflow.com/questions/65802392/pushing-split-json-back-into-json-object January 20, 2021 at 10:47AM

没有评论:

发表评论