Google Sheet - Split Cell contents into rows and columns

后端 未结 2 1559
[愿得一人]
[愿得一人] 2021-02-11 11:56

Linked Google Sheet: https://docs.google.com/spreadsheets/d/1j2P2V0SCiE7QtK7kdCorpLfYQPFRghKMw4tuCYbqce0/edit?usp=sharing

I have a form that outputs all products and qua

2条回答
  •  抹茶落季
    2021-02-11 12:22

    You might be interested in a more general solution, rather than one that needs to rely on knowing the specific phrased in the input strings.

    This kvStringToArray() function will return an array that can be written directly to a spreadsheet use Range.setvalues(). It's pure JavaScript, so it can also be used outside of the Google Apps Script environment.

    A RegExp is used to successively identify key:value pairs in the input data, and the function assumes that there are "rows" of information that can be identified by repeats of already-discovered "keys".

    var formInput = "Product: NF900XC, Quantity: 3 Product: NF900, Quantity: 2 Product: N1930CB, Quantity: 2 Product: N2120, Quantity: 1 Product: NLPCR200, Quantity: 2 Product: N272, Quantity: 2";
    snippet.log(
      JSON.stringify(
        kvStringToArray(formInput)));
    
    /**
     * Convert a given string of key:value pairs into a two-dimensional
     * array, with keys as headers, and "items" as rows.
     * From: http://stackoverflow.com/a/34847199/1677912
     *
     * @param {string} str    A string containing key:value pairs.
     *
     * @returns {string[][]}  A two-dimensional array of strings.
     */
    function kvStringToArray( str ) {
      var re = /\s*(\w*?)\s*:\s*([^,\s]*)/g,  // See https://regex101.com/r/kM7gY1/1
          arr,           // array to capture key:value pairs
          data = [],     // array to return table
          row = [],      // array for building table rows
          headers = [];  // array of unique keys, for table header
      
      // Use a RegEx to identify individual key:value pairs
      while ((arr = re.exec(str)) !== null) {
        var key = arr[1];   // $1 matches key
        var value = arr[2]; // $2 matches value
        // Check if we should start a new row
        if (headers.indexOf(key) == 0) {
          data.push(row);
          row = [];
        }
        // Save this value in row
        row.push(value);
        // If this is the first time we've seen this key, add it to headers.
        if (headers.indexOf(key) == -1) headers.push(key);
      }
      data.push(row);  // save last row
      data.unshift(headers); // add headers
    
      return data;
    }
    
    

提交回复
热议问题