Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How add an Object to this JSON in Javascript?

I have this JSON in a File:

{
  "user1": {
    "id": 1,
    "nVote": 0,
    "comment": ""
  }
}

And I would like to add an object user2 with the same parameters and corresponding values.

function json2Array(json) {
  var result = [];
  var keys = Object.keys(json);
  keys.forEach(function (key) {
    result.push(json[key]);
  });
  return result;
}

const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8'));
const arObj = json2Array(obj);

let user = [];
user['user2'] = {
  "id": 2,
  "nVote": 1,
  "comment": 'test'
};

arObj.push(user);

that result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    [
      { id: 1, nVote: 0, comment: '' },
      [ user2: { id: 2, nVote: 1, comment: 'test' } ]
    ]

But I would like to ultimately this result:

    {
      "user1": { id: 1, nVote: 0, comment: '' },
      "user2": { id: 2, nVote: 1, comment: 'test' }
    }

>Solution :

If the result you want is an object, there’s no need to convert it to an array. Just add a property to the object.

const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8'));
obj['user2'] = {
  "id": 2,
  "nVote": 1,
  "comment": 'test'
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading