我有一组对象。
当我将一个新对象推入我的父函数时,我希望它:
否则:
这听起来很简单,我的逻辑似乎正好在我脑海中,但我似乎无法按照上面的描述进行操作,而是尝试通过传递一个具有相同键的对象来更新属性。在数组中已经作为函数的参数,覆盖它的新值并推送一个新的副本.....,这里是相关的代码:
var filters = [];
function addFilterToFiltersArray(obj) {
var isValidFilter,
filterKey = "",
filterEnglishReadable = "",
hasBeenAjaxed;
for (var prop in knownFilters) {
//is the filter a valid key in the knownFilters object?
if (obj.key === prop) {
//if so set it as valid and create a variable to hold the key and another for the value
isValidFilter = true,
filterKey = prop,
filterEnglishReadable = knownFilters[prop];
//check if the filters array has elements in it
if (filters.length > 0) {
//if it does, loop the array
for (var i = 0; i < filters.length; i++) {
//check if any of the array objects have a key that matches the pushed filter
console.log(obj)
if (filters[i].key === obj.key) {
console.log('keys are equal, update', filters[i].key, obj.key)
//if it does, check if the value has changed in the newly pushed version
if (filters[i].value === obj.value) {
//if the value has not changed, it is in the array and there is no update necessary
hasBeenAjaxed = true;
} else {
//otherwise we overwrite the value with the new value
filters[i].value = obj.value;
//since we have now updated the value of the object in the filters array
//we not set the hasBeenAjaxed variable to false so that ajax runs with the new value
hasBeenAjaxed = false;
}
} else {
console.log('keys are not equal, push', filters[i].key, obj.key, obj)
//otherwise, the filter key is not in the array and so we set the hasBeenAjaxed variable as such
hasBeenAjaxed = false;
filters.push(obj);
}
}
} else {
//in this case, the array is empty and thus we can assume that the filter isnt there, obviously.
hasBeenAjaxed = false;
filters.push(obj);
}
//if the value was updated, the filter wasnt found in the above loop, we push the new value/key-value and run ajax
if (hasBeenAjaxed === false) {
//ajax
//pass to the dom builder
addFilterToDOM(filterEnglishReadable);
}
} else {
//otherwise its not valid
isValidFilter = false;
filterEnglishReadable = "";
}
}
}
也许我只是遗漏了一些小事,但是,是的,有什么想法吗?