Home Ask Login Register

Developers Planet

Your answer is one click away!

Paulo C February 2016

Find And Replace Items In A Json file

Hello I'm trying to update items stored in a json file in a Express App basically i'm reading the contents of the json file updating the item fetched by Id and writing to the file the updated item.Problem?? It's appending the updated item so i get a duplicated.I can't see where is the error?? Help?

Here is the code:

posts.json

[
    {
        "name": "first name",
        "description": "test first description",
        "slug": "first-name",
        "id": "2f065d59"
    },
   {
        "name": "second name",
        "description": "test second description",
        "slug": "second-name",
        "id": "0071b034"
    }
]

create-update-delete.js

var express = require('express');
var Creatordb = require('./database/posts.json');
var fs = require('fs');
var uuid = require('node-uuid');
var _ = require('lodash');

 //Create The Item           
var add = function (item) {
  var id = uuid.v4();
  item.id = id;
  Creatordb[item.id] = item;
  var outputFilename = './database/posts.json'; 

  function appendObject(obj){
    var configFile = fs.readFileSync(outputFilename);          
    var config = JSON.parse(configFile); 

    config.push(obj);           

    var configJSON = JSON.stringify(config, null, 4);

    fs.writeFileSync(outputFilename, configJSON);

  }
  appendObject(item);
};

//Get The Item by Id
var getById = function (id) {
  for(var i=0;i<Creatordb.length;i++) {
    var id = Creatordb[i].id;
  }
  return id;
};

//Update The Item 
var update = function (item) {        
  var outputFilename = './database/posts.json'; 
  var configFile = fs.readFileSync(outputFilename);

  var config = JSON.parse(configFile); 


  //using lodash??
 var index = _.indexOf(config, _.find(config, item));

 config.splice(index, 1, item);

  var configJSON = JSON.stringify(config, null, 4);

  fs.writeFileSync(outputFilename, configJSON);

};

If i update an item the posts.json will look like t

Answers


Festo February 2016

There is two problems:

  1. You use push what is insert a new item into your list, this is the reason of the 'duplication'

  2. config[item.id] = item; is not a valid reference. Your config is not like this:

    ["0071b034": { name: "Foo"}]

So the keys in config are 0,1,2 and not the item.id

I suggest to use lodash. There are a lots of useful functions, but if you stick this implementation, use this:

function findIndex(collection, id) {
  for(var i=0; i<collection.length; i++) {
    if (collection[i].id === id) {
      return i;
    }
  }
}

// In your update function
var index = findIndex(config, item.id);
config[index] = item;

Post Status

Asked in February 2016
Viewed 1,275 times
Voted 8
Answered 1 times

Search




Leave an answer


Quote of the day: live life