Home  >  Q&A  >  body text

How can I add an object to this JSON in Javascript?

I have this JSON in the file:

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

I want 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);

result:

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

But I hope to end up with this result:

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

P粉476883986P粉476883986259 days ago307

reply all(2)I'll reply

  • P粉904405941

    P粉9044059412024-02-04 15:15:16

    All you have to do is treat the json object as an array

    Simple

    think about it

    [
    {user1:{"id":2,"nVote":1,...}}
    {user2:{"id":2,"nVote":1,...}}
    ]
    

    so

    const obj = []
    obj.push({user1:{id:2,nVote:2})
    obj.push(({user2:{id:3,nVote:1})

    This is what you need, then you can use fs to extract it to a json file for storage

    reply
    0
  • P粉536909186

    P粉5369091862024-02-04 11:46:41

    If the result you want is an object, there is 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'
    };

    reply
    0
  • Cancelreply