在现有JSON中添加另一个对象

时间:2018-06-13 01:57:39

标签: javascript json object

我基本上试图将数据保存到json中,

基本上是这样的:

{
"userid1": {
    "name" : "user1",
    "wins" : "21",
    "loss" : "0",
    "leaderboard" : "1"
},
"userid2": {
    "name" : "user2",
    "wins" : "0",
    "loss" : "0",
    "leaderboard" : "0"
},
// how do you push another object, let's say; this time; userid3 which would look like this. 

// "userid3": {
//  "name" : "user3",
//  "wins" : "0",
//  "loss" : "0",
//  "leaderboard" : "0"
// }

// (using javascript, from another file; let's say it's called "datasave.js") 
// here?
}

我想添加另一个对象而不是重写整个对象。我该怎么做?

这是一个自己的json文件,还有另一个.js文件,以及解析json文件的地方。我想从那里添加对象。

我现在已经以某种方式工作了。 imgur.com/zQTJ11K;那里有一个名为" id"并且id为userId,如何更改" id"在图片中给userId?

3 个答案:

答案 0 :(得分:0)



output = {
  "userid1": {
      "name" : "user1",
      "wins" : "21",
      "loss" : "0",
      "leaderboard" : "1"
  },
  "userid2": {
      "name" : "user2",
      "wins" : "0",
      "loss" : "0",
      "leaderboard" : "0"
  }
};

u3 = {
        "name" : "user2",
        "wins" : "0",
        "loss" : "0",
        "leaderboard" : "0"
     };
          
output.userid3 = u3;

console.log(output);




答案 1 :(得分:0)

您可以使用Object.assign

const result = Object.assign(data, objToAdd);

bracket notation

data['userId3'] = obj

或点符号

data.userId3 = obj



const data = {
  "userid1": {
    "name": "user1",
    "wins": "21",
    "loss": "0",
    "leaderboard": "1"
  },
  "userid2": {
    "name": "user2",
    "wins": "0",
    "loss": "0",
    "leaderboard": "0"
  }
}

const obj = {
  "userid3": {
    "name": "user3",
    "wins": "0",
    "loss": "0",
    "leaderboard": "0"
  }
}

Object.assign(data, obj);

console.log(data)




答案 2 :(得分:-1)

您可以使用js import将import另一个文件放入您的文件中。您也可以导入您的对象

您可以使用javascript spread syntax将两个对象合并为一个

var object1={name:"xyz"}
var object2={surname:"abc"}
then object1={...object1,...object2} // object={name:"xyz",surname:"abc"}