我有这个 JSON 对象:
var collection = {
"123":{
"name": "Some Name",
"someArray": [
"value 0",
"value 1"
]
},
"124":{
"name": "Some Name"
},
我有一个方法可以更新并返回集合,例如:
function updateCollection(id, property, value){
return collection;
}
假设方法调用是这样的:
updateCollection(124, someArray, "value 3");
我应该如何更新?我已经写的是:
function updateCollection(id, property, value){
if(collection[id].hasOwnProperty(property)){
collection[id][property].push(value);
}
else{
//need help here
}
return collection;
}
调用方法后的预期输出 updateCollection(124, someArray, "value 3");
应该是:
"124":{ "name": "Some Name", "someArray": [ "value 3", ] }
最佳答案
创建一个仅包含value
的新数组并将其分配给collection[id][property]
:
function updateCollection(id, property, value) {
collection[id] = collection[id] || {}; // if "id" doesn't exist in collection
if (collection[id].hasOwnProperty(property) {
collection[id][property].push(value);
} else {
collection[id][property] = [value]
}
return collection;
}
关于javascript - 如果 JSON 对象不存在,则将其添加到该对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55295273/