Kirill Vorobjov Kirill Vorobjov - 3 months ago 15
JSON Question

Search for the biggest id and add new biggest id in JSON file ( NodeJS )

When performing an insert operation i'm trying to add the next biggest id in to JSON file. The thing is that when i have for example id: 13 , it makes new object with id: 14 and rewrites old object with id: 14, after that i have 2 objects with the same id.

What did i wrong ?

fs.readFile("DB.json", "utf8", function (err, data) {
var jsonFileArr = []; // DB.json objects
jsonFileArr = JSON.parse(data);


function maxValue(jsonFileArr, prop) { // Searches for the biggest numbers in DB.json
var max = "";
for (var i = 0; i < jsonFileArr.length ; i++) {
if (!max || parseInt(jsonFileArr[i][prop]) > parseInt(max[prop]))
max = jsonFileArr[i];
}
return max;
}

var maxID = maxValue(jsonFileArr, "id"); //Biggest ID

console.log("\r\nBiggest ID : " + maxID.id);
newID = ++maxID.id;

var updateData = {
id : newID, // new ID
name: POST.name, // Objects that come from POST request when i add new row in the table
alter: POST.alter,
produkt: POST.produkt,
anzahl: POST.anzahl
}

jsonFileArr.push(updateData);
var newUsers = JSON.stringify(jsonFileArr);
fs.writeFile("JSON/DB.json", newUsers, "utf8");
console.log("New user has been added with ID : " + newID);

Answer

Written in vanilla Javascript and so should work in Node.js directly.

var jsonObj = [{
  "id": 3,
  "player": "Carmelo Anthony",
  "team": "New York Knicks"
}, {
  "id": 1,
  "player": "Andre Drummond",
  "team": "Detroit Pistons"
}, {
  "id": 2,
  "player": "Anthony Davis",
  "team": "New Orleans Pelicans"
}]

function getNextId(obj) {
  return (Math.max.apply(Math, obj.map(function(o) {
    return o.id;
  })) + 1);
}


alert('Next ID is ' + getNextId(jsonObj));

Comments