我有这个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;
}
答案 0 :(得分:5)
仅使用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;
}
答案 1 :(得分:2)
我会向前迈一步,为不存在的任何id
插入一个新对象,并在必要时为property
创建一个新数组。
function updateCollection(id, property, value) {
collection[id] = collection[id] || {};
collection[id][property] = collection[id][property] || [];
collection[id][property].push(value);
return collection;
}
答案 2 :(得分:0)
这里是您的代码。
var collection = {
"123":{
"name": "Some Name",
"someArray": [
"value 0",
"value 1"
]
},
"124":{
"name": "Some Name"
}
};
function updateCollection(id, property, value){
var _coll = collection.hasOwnProperty(id) ? collection[id] : {};
_coll[property] = value;
collection[id] = _coll;
return collection;
}
console.log(updateCollection(124, "somearray", ['1','2']));
答案 3 :(得分:0)
我已经更新了您的代码,它对于不存在数组或值的情况应该会更好
var collection = {
"123":{
"name": "Some Name",
"someArray": [
"value 0",
"value 1"
]
},
"124":{
"name": "Some Name"
}};
function updateCollection(id, property, value) {
if (collection[id] && collection[id][property]) {
collection[id][property].push(value);
}
else
{
collection[id] = {};
collection[id][property] = [value]
}
return collection;
}
updateCollection(124, "someArray", "value 3");
updateCollection(125, "someArray", "value 3");
console.log(collection);