0

I have a local JSON file under the path static/json/test.json. Its content is [{"id": 12}, {"id": 44}]. I want to read it, delete the object of the index i from it and rewrite the file so if for example i = 0 the new content should be [{"id": 44}].

What i have tried so far:

let i = 0;

fs.readFile("static/json/test.json", "utf8", function(err, data) {
    let obj = JSON.parse(data); // obj is now [{"id": 12}, {"id": 44}]
    delete obj[i];
    fs.writeFile("static/json/test.json", JSON.stringify(obj), "utf8");
    // test.json should now be [{"id": 44}], but its [null, {"id": 44}]
});

If I do this, the content of test.json isn't [{"id": 44}], it's [null, {"id": 44}].

I've read about using obj.splice(i, 1); instead of delete obj[i];, but for some reason that doesnt do anything, without me recieving any errors.

How do I remove the object of index i of this JSON array without leaving null behind?

Edit:

Thanks for the fast answers! Typically obj.splice(i, 1); should work, the cause why it doesn't for me has to have to do with my setup. The working answer for me is

let i = 0;

fs.readFile("static/json/test.json", "utf8", function(err, data) {
    let obj = JSON.parse(data); // obj is now [{"id": 12}, {"id": 44}]

    delete obj[i];
    obj = obj.filter(item => item);

    fs.writeFile("static/json/test.json", JSON.stringify(obj), "utf8");
    // test.json is now [{"id": 44}]
});
1
  • 1
    Using the code you show here with obj.splice(i, 1) instead of delete obj[i] works perfectly fine and results in test.json to be [{"id":44}]. There must be an other problem with your setup that should be fixed instead of looking for a workaround. What is the console output when you write obj.splice(i, 1); console.dir(JSON.stringify(obj)); instead of delete obj[i] Commented Oct 27, 2018 at 15:45

2 Answers 2

2

You can do delete and filter out undefined

const obj= [{"id": 12}, {"id": 44}]
delete obj[0];
console.log(obj.filter(item => item));

BUT splice() works OK

const obj= [{"id": 12}, {"id": 44}]
obj.splice(0, 1);
console.log(obj);

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

2 Comments

If you're filtering, why bother with delete?
Yes I agree, only filter will do the trick. But as OP used already delete, So I just do the undefined filter
0

You can use Array.splice to do this

// The item index to remove
let index = 0;
let arr = [{id: 12}, {id: 44}];
arr.splice(index,1);
console.log("Array after removing item", arr);

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.