我有一个JSON
变量。
{
"name": "test name",
"place": "test place",
"participants": {
"one": {
"lat_long": "0.0,0.0",
"name": "name 1"
},
"two": {
"lat_long": "0.0,0.0",
"name": "name 2"
}
},
"lat_long": "0.0,0.0"
}
如何使用javascript
将以下数据添加到上述变量的particpants
键中
"theree": {
"lat_long": "0.0,0.0",
"name": "name 3"
}
这样我的新JSON
变量就像这样
{
"name": "test name",
"place": "test place",
"participants": {
"one": {
"lat_long": "0.0,0.0",
"name": "name 1"
},
"two": {
"lat_long": "0.0,0.0",
"name": "name"
},
"theree": {
"lat_long": "0.0,0.0",
"name": "name 3"
}
},
"lat_long": "0.0,0.0"
}
如何识别JSON对象和JSON数组?
答案 0 :(得分:4)
由于您没有显示实际的合法javascript,只是数据片段,因此还不完全清楚您要问的是什么。所以,我已经提出了3个关于你可能要问的猜测:
如果您的初始数据名称为data
,请执行以下操作:
var data = {
"name": "test name",
"place": "test place",
"participants": {
"one": {
"lat_long": "0.0,0.0",
"name": "name 1"
},
"two": {
"lat_long": "0.0,0.0",
"name": "name 2"
}
},
"lat_long": "0.0,0.0"
};
然后,您可以添加theree
属性,如下所示:
data.participants.theree = {
"lat_long":"0.0,0.0",
"name": "name 3"
};
如果您的键值在变量中(我们称之为名为key
的变量),那么您使用[key]
语法:
var key = "theree";
data.participants[key] = {
"lat_long":"0.0,0.0",
"name": "name 3"
};
如果您真正开始的是这样的对象:
var addData = {
theree: {
"lat_long":"0.0,0.0",
"name": "name 3"
}
}
你不知道theree
的值,你需要从该对象获取它,然后由于你需要枚举addData
对象的属性并添加每个一个到participants
对象:
// add all items from the addData object to the participants object
// this is essentially a merge of addData into participants
for (var prop in addData) {
if (addData.hasOwnProperty(prop) {
data.participants[prop] = addData[prop];
}
}
请注意,尽管您在问题中使用了array
和push
这两个术语,但此处没有数组,因此您不使用.push()
方法。您只需向对象添加属性,可以通过直接分配添加到新属性名称。
另外,请注意JSON是一种专为数据交换而设计的文本格式。你在这里有一个javascript对象,它与JSON不同。
答案 1 :(得分:1)
试试这个:
var newdata = {"three": {
"lat_long": "0.0,0.0",
"name": "name 3"
}
};
var newKey = Object.keys(newdata);
data.participants[newKey[0]] = newdata[newKey[0]];
console.log(data);
您的数据可能是:
1. var newdata = {"five": {
"lat_long": "0.0,0.0",
"name": "name 3"
}
};
2. var newdata = {"four": {
"lat_long": "0.0,0.0",
"name": "name 3"
}
};
它不依赖于密钥。