【问题标题】:JS - Pushing data into JSON structure using forEach loops on ArraysJS - 使用数组上的 forEach 循环将数据推送到 JSON 结构中
【发布时间】:2018-01-04 21:13:08
【问题描述】:

如果 JSON 值与我输入的数组 (inputedJurisdictionArray) 中的元素匹配,我正在尝试提取 JSON 值(从名为 jsonWithListOfStatesAndCounters 的结构中)。我输入的数组包含包含单个或多个状态名称的字符串值(即var inputedJurisdictionArray = ["Iowa", "California, Indiana, Delaware", "Florida"])。这个数组中的奇异状态值在最后正常处理,但多个状态值是它变得棘手的地方。我正在使用split() 将它们转换为另一个数组,以便它们可以被一个一个地处理。每当此输入数组中的一个状态与jsonWithListOfStatesAndCounters 中的“状态”值匹配时,我会将其提取到另一个 JSON 结构中,并在每个块的末尾将其推送到我的初始变量 myJurisdictionJSON 中。我遇到的问题是,一旦这些 forEach 循环完成,我仍然会在 myJurisdictionJSON 中留下我的原始值,而不是应该提取的 val 和 counter。 jsonWithListOfStatesAndCounters 肯定包含应该与我的inputedJurisdictionArray 的元素匹配的值,但信息不会被推送到myJurisdictionJSON。我究竟做错了什么?任何提示/指针都会有所帮助。

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;
                    }
                }   
            }       
        });

【问题讨论】:

    标签: javascript arrays json node.js foreach


    【解决方案1】:

    我不完全确定输出是你想要的,但它很接近。

    // input data as per your example
    let inputedJurisdictionArray = [
      'Iowa',
      'California, Indiana, Delaware',
      'Florida'
    ];
    
    // I had to make this part up. It's missing from the example
    let jsonWithListOfStatesAndCounters = [{
        jurisdictionCounter: 2,
        jurisdictionState: 'Florida'
      },
      {
        jurisdictionCounter: 4,
        jurisdictionState: 'Indiana'
      },
      {
        jurisdictionCounter: 3,
        jurisdictionState: 'Texas'
      }
    ];
    
    // first, fix up inputedJurisdictionArray
    // reduce() loops over each array element
    // in this case we're actually returning a LARGER
    // array instead of a reduced on but this method works
    
    // There's a few things going on here. We split, the current element
    // on the ','. Taht gives us an array. We call map() on it.
    // this also loops over each value of the array and returns an
    // array of the same length. So on each loop, trim() the whitespace
    // Then make the accumulator concatenate the current array.
    // Fat arrow ( => ) functions return the results when it's one statement.
    inputedJurisdictionArray = inputedJurisdictionArray.reduce(
      (acc, curr) => acc.concat(curr.split(',').map(el => el.trim())), []
    );
    
    // now we can filter() jsonWithListOfStatesAndCounters. Loop through
    // each element. If its jurisdictionState property happens to be in
    // the inputedJurisdictionArray array, then add it to the
    // myJurisdictionJSON array.
    let myJurisdictionJSON = jsonWithListOfStatesAndCounters.filter(el =>
      inputedJurisdictionArray['includes'](el.jurisdictionState)
    );
    
    console.log(myJurisdictionJSON);

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 2022-01-27
      • 1970-01-01
      • 2015-11-22
      • 2019-02-23
      • 1970-01-01
      • 2014-10-11
      • 2017-04-24
      • 1970-01-01
      相关资源
      最近更新 更多