Можно ли построить строку с использованием условных сокращений, как это? - PullRequest
0 голосов
/ 15 ноября 2018

Я пытаюсь добавить некоторые параметры в свой URL на основе выпадающих списков, я хочу, чтобы код был максимально коротким и приятным, поэтому я пытаюсь построить строку для параметров, которая пропускает все переменные, которые являются пустыми поэтому они не добавляются в строку URL. Ниже я попробовал:

$(function() {
  var product = 'shirt',
      size = 'large',
      color = 'blue',
      custom = '';
      
  var urlParams = (product === '') ? '' : 'product=' + product + '&' + (size === '') ? '' : 'size=' + size + '&' + (color === '') ? '' : 'color=' + color + '&' + (custom === '') ? '' : 'custom=' + custom;
  
  console.log(urlParams);
  
  // Go to results page
  // location.href = 'results?' + urlParams;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Ожидаемый результат urlParams:

product=shirt&size=large&color=blue

К сожалению, это возвращает пустую строку. Можно ли построить параметры, как это? Или есть какой-нибудь лучший способ сделать это?

Ответы [ 3 ]

0 голосов
/ 15 ноября 2018

Вы можете проверить значение и взять логическое И для форматированной строки.

var urlParams = (product && 'product=' + product + '&') +
                (size && 'size=' + size + '&') +
                (color && 'color=' + color + '&') +
                (custom && 'custom=' + custom);

Другой подход заключается в использовании объекта, фильтрации истинных значений и построении форматированной строки с помощью строки шаблона.

function getString(object) {
    return Object
        .entries(object)
        .filter(([, v]) => v)
        .map(([k, v]) => `${k}=${v}`)
        .join('&');
}

var product = 'foo', 
    size = '42',
    color = '',
    data = { product, size, color };
    
    
console.log(getString(data))
0 голосов
/ 15 ноября 2018

const params = {
    product: 'shirt',
    size: 'large',
    color: '',
    custom: null
}
const valid = p => k => typeof p [k] === 'string' && p [k].length > 0
let queryString = Object.keys (params).filter (valid (params)).map (k => `${k}=${params[k]}`).join ('&')

console.log (queryString)
0 голосов
/ 15 ноября 2018

Паразиты имеют значение!

Проблема в том, что вы не смотрите на старые. custom === "" становится правдой, и тогда все ваше состояние рушится. Лучший способ сделать это:

(function() {
  var product = 'shirt',
    size = 'large',
    color = 'blue',
    custom = '';

  var urlParams = ((product === '') ? '' : 'product=' + product) + '&' + ((size === '') ? '' : 'size=' + size) + '&' + ((color === '') ? '' : 'color=' + color) + '&' + ((custom === '') ? '' : 'custom=' + custom);

  console.log(urlParams);

  // Go to results page
  // location.href = 'results?' + urlParams;
})();

Теперь вы можете видеть, что есть & с. Лучшая версия будет:

(function() {
  var product = 'shirt',
    size = 'large',
    color = 'blue',
    custom = '';

  var urlParams = ((product === '') ? '' : 'product=' + product) + '&' + ((size === '') ? '' : 'size=' + size) + '&' + ((color === '') ? '' : 'color=' + color) + '&' + ((custom === '') ? '' : 'custom=' + custom);
  urlParams = urlParams.replace(/^\&+|\&+$/g, '');
  console.log(urlParams);

  // Go to results page
  // location.href = 'results?' + urlParams;
})();

Лучше всего использовать массивы и .join() с.

(function() {
  var product = 'shirt',
    size = 'large',
    color = 'blue',
    custom = '';

  var urlParams = [
    ((product === '') ? '' : 'product=' + product),
    ((size === '') ? '' : 'size=' + size),
    ((color === '') ? '' : 'color=' + color),
    ((custom === '') ? '' : 'custom=' + custom)
  ];
  urlParams = urlParams.join("&").replace(/^\&+|\&+$/g, '');
  console.log(urlParams);

  // Go to results page
  // location.href = 'results?' + urlParams;
})();
...