-4

I need some help to add a new element at end of the JSON array in nodejs

Sample JSON Array

[{
  "subject": "physics",
  "student_id": "2569",
  "values": "0.152,0.228,0.218"
}, {
  "subject": "maths",
  "student_id": "1236",
  "values": "0.146,0.22,0.212"
}, {
  "subject": "chemistry",
  "student_id": "4569",
  "values": "0.159,0.234,0.224"
}, {
  "subject": "physics",
  "student_id": "1478",
  "values": "0.16,0.235,0.225"
}]

Expected Result should be

[{
  "subject": "physics",
  "student_id": "2569",
  "values": "0.152,0.228,0.218"
}, {
  "subject": "maths",
  "student_id": "1236",
  "values": "0.146,0.22,0.212"
}, {
  "subject": "chemistry",
  "student_id": "4569",
  "values": "0.159,0.234,0.224"
}, {
  "subject": "physics",
  "student_id": "1478",
  "values": "0.16,0.235,0.225"
}, 
lastSyncTime: 1550467657366]

Please provide me with a simple solution.

  • That isn't a JSON array – Aluan Haddad Feb 18 '19 at 06:18
  • U can't add an object like that to an array. use array.push({lastSyncTime:155}) – Sagar Acharya Feb 18 '19 at 06:33
  • Possible duplicate of [Adding a new array element to a JSON object](https://stackoverflow.com/questions/18884840/adding-a-new-array-element-to-a-json-object) – cantuket Feb 18 '19 at 06:35
  • The simple solution in three simple steps: 1. parse the JSON, get an array; 2. push the new element at the end of the array; 3. generate a new JSON using the updated array. Your expected result is not a valid JSON. An array cannot contain named properties. – axiac Feb 18 '19 at 06:46

1 Answers1

0

You can simply do it with javaScript

var myArray = [{
  "subject": "physics",
  "student_id": "2569",
  "values": "0.152,0.228,0.218"
}, {
  "subject": "maths",
  "student_id": "1236",
  "values": "0.146,0.22,0.212"
}, {
  "subject": "chemistry",
  "student_id": "4569",
  "values": "0.159,0.234,0.224"
}, {
  "subject": "physics",
  "student_id": "1478",
  "values": "0.16,0.235,0.225"
}];

myArray.push({lastSyncTime: 1550467657366});

console.log(myArray);

And the result will be

[{
  "subject": "physics",
  "student_id": "2569",
  "values": "0.152,0.228,0.218"
}, {
  "subject": "maths",
  "student_id": "1236",
  "values": "0.146,0.22,0.212"
}, {
  "subject": "chemistry",
  "student_id": "4569",
  "values": "0.159,0.234,0.224"
}, {
  "subject": "physics",
  "student_id": "1478",
  "values": "0.16,0.235,0.225"
}, 
{lastSyncTime: 1550467657366}];

You can also get the last item using

var lastSyncTime = myArray[myArray.length - 1].lastSyncTime;
console.log(lastSyncTime); // That is: 1550467657366

Or if you want to find an object in a list using lodash, check the link below

How to use lodash to find and return an object from Array?

Masoud Darvishian
  • 3,754
  • 4
  • 33
  • 41