入力された配列(inputedJurisdictionArray
)の要素と一致するJSON値(構造体jsonWithListOfStatesAndCounters
)を抽出しようとしています。入力した配列に、単数または複数の州名(例:var inputedJurisdictionArray = ["Iowa", "California, Indiana, Delaware", "Florida"]
)が含まれています。この配列内の特異状態値は、最後に正常に処理されますが、複数の状態値は扱いにくい場所です。私はsplit()
を使って別の配列に変換し、1つずつ処理できるようにしています。この入力された配列の状態の1つがjsonWithListOfStatesAndCounters
の "状態"の値と一致するたびに、別のJSON構造に展開して、ブロックの最後に初期変数myJurisdictionJSON
にプッシュします。私が抱えている問題は、これらのforEachループが完了すると、抽出されるべきvalとcounterではなく、元の値がmyJurisdictionJSON
に残っているということです。 jsonWithListOfStatesAndCounters
には、私のinputedJurisdictionArray
の要素と一致するはずの値が含まれていますが、情報はmyJurisdictionJSON
にプッシュされていません。私は間違って何をしていますか?任意のヒント/ポインタが役立ちます。JS - 配列のforEachループを使用してデータをJSON構造にプッシュする
var myJurisdictionJSON = [{
jurisdiction_val: 'jurisdiction_val',
jurisdiction_counter: 'jurisdiction_counter'
}];
inputedJurisdictionArray.forEach(function each(item) {
if (Array.isArray(item)) {
item.forEach(each);
} else {
var jurisdictionInput = item;
jsonWithListOfStatesAndCounters.forEach(function each(item) {
if (Array.isArray(item)) {
item.forEach(each);
} else {
if (jurisdictionInput.includes(",") === true){//Checking if more than one jurisdiction in string
var jurisdictionArr = jurisdictionInput.split(", ");
var jurisdictionCounter = item.jurisdictionCounter;
var jurisdictionState = item.jurisdictionState;
jurisdictionArr.forEach(function(element) {
if (myJurisdictionJSON.jurisdiction_counter == 'jurisdiction_counter'){ // If nothing is pushed into our predefined JSON object
if (jurisdictionState.toLowerCase() == trim(element.toLowerCase())) {
var jurisdictionJSON_inner = {
jurisdiction_val: element,
jurisdiction_counter: jurisdictionCounter
};
myJurisdictionJSON.push(jurisdictionJSON_inner);
return;
}
}else if (myJurisdictionJSON.jurisdiction_counter != 'jurisdiction_counter'){ // if an item has been pushed into myJurisdictionJSON, append the next items
var jurisdictionCounter = item.jurisdictionCounter;
var jurisdictionState = item.jurisdictionState;
if (jurisdictionState.toLowerCase() == trim(jurisdictionInput.toLowerCase())) {
jurisdictionJSON_inner.jurisdiction_val = jurisdictionJSON_inner.jurisdiction_val + ", " + jurisdictionInput;
jurisdictionJSON_inner.jurisdiction_counter = jurisdictionJSON_inner.jurisdiction_counter + ", " + jurisdictionCounter;
myJurisdictionJSON.push(jurisdictionJSON_inner);
return;
}
}
});
}
else{// if only one jurisdiction state in jurisdictionInput string
var jurisdictionCounter = item.jurisdictionCounter;
var jurisdictionState = item.jurisdictionState;
if (jurisdictionState.toLowerCase() == trim(jurisdictionInput.toLowerCase())) {
var jurisdictionJSON_inner = {
jurisdiction_val: jurisdictionInput,
jurisdiction_counter: jurisdictionCounter
};
myJurisdictionJSON.push(jurisdictionJSON_inner);
return;
}
}
}
});