我有一个oInfoModal对象如下。
var oInfoModal = {"modals" : [
{"myID" : 4,"myVals" : [{2,5,7}]},
{"myID" : 9,"myVals" : [{13,8,6}]},
{"myID" : 6,"myVals" : [{1}]}
] };
我尝试做的是处理一些传入数据并检查该传入数据是否存在值。 即如果myID为6,则将myIdx添加到myVals。 但是如果myID为6并不存在,那么构建子对象并将其推入oInfoModal。
function processFunction(idx){
var myIdx = 3; //
var myID = 6;
var existsMyID = $.map(oInfoModal.modals, function(elem, index) {
if (elem.myID == myID){
// myID is found in oInfoModal
return true;
} else{
// myID not found in oInfoModal
return false;
}
});
if (existsMyID){
// myID is found in oInfoModal. push myIdx to myVals for myID=6 in oInfoModal
// How?
} else {
// myID not found in oInfoModal. Create and push full object to oInfoModal
var myObj = {"myID" : myID,"myVals" : myIdx};
oInfoModal.modals.push( myObj ); // not working
}
}
我有一壶咖啡,所以不是这样。我错过了什么?
答案 0 :(得分:0)
myVals
中的值不正确。您需要使用array#find
来检查数组中是否存在值。如果存在,则可以推送新值,否则添加具有id和value的新对象。
var oInfoModal = {"modals" : [{"myID" : 4,"myVals" : [2,5,7]},{"myID" : 9,"myVals" : [13,8,6]},{"myID" : 6,"myVals" : [1]}]};
function processFunction(idx){
var myIdx = 3; //
var myID = 20;
var existsMyID = oInfoModal.modals.find(function(o){
return o.myID === myID;
});
if(existsMyID)
existsMyID.myVals.push(myIdx);
else {
var myObj = {"myID" : myID, "myVals" : [myIdx]};
oInfoModal.modals.push(myObj);
}
}
processFunction(null);
console.log(oInfoModal);