-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.

4
  • That isn't a JSON array Commented Feb 18, 2019 at 6:18
  • U can't add an object like that to an array. use array.push({lastSyncTime:155}) Commented Feb 18, 2019 at 6:33
  • Possible duplicate of Adding a new array element to a JSON object Commented Feb 18, 2019 at 6: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. Commented Feb 18, 2019 at 6:46

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.