如何在JavaScript中向此JSON添加一个对象?

huangapple go评论148阅读模式
英文:

How add an Object to this JSON in Javascript?

问题

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

英文:

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:

    [
      { 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' }
    }

答案1

得分: 0

如果您想要的结果是一个对象,就不需要将它转换为数组。只需向对象添加属性。

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

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'
};

答案2

得分: 0

你只需将JSON对象视为数组

简单

考虑这个

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

所以

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

这就是你需要的,然后你可以使用fs将其存储到一个JSON文件中


<details>
<summary>英文:</summary>

all you have to do is to treat the json object as array

simply

consider this

```json
[
{user1:{&quot;id&quot;:2,&quot;nVote&quot;:1,...}}
{user2:{&quot;id&quot;:2,&quot;nVote&quot;:1,...}}
]

so

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

that's all you need then you can store that using the fs to extract it to a json file

huangapple
  • 本文由 发表于 2023年6月22日 07:01:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定