Javascript 将对象转换为 URL

Javascript Convert an Object to a URL

我有一个看起来像这样的对象:

activeFilters: {
    category: {
        '1': 'View All',
        '2': ' Flats'
    },
    brand: {
        '1': 'Fits'
    }
}

我想映射对象并将它们用作 URL 参数。最终结果将如下所示:

https://api.websiteurl.com/products?category=1,2&brand=1

我正在使用react,我可以使用lodash。需要有关实现此目标的最佳方法的帮助

您可以利用Object.entries and map达到想要的效果

const filters = {
  activeFilters: {
    category: {
      "1": "View All",
      "2": " Flats",
    },
    brand: {
      "1": "Fits",
    },
  },
};

const queryString = Object.entries(filters.activeFilters)
  .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(Object.keys(v))}`)
  .join("&");

const url = "https://api.websiteurl.com/products";

// Thanks Dai for this suggestion to encode the path.
const result = `${url}?${queryString}`;
console.log(result);

const activeFilters = {category: {'1': 'View All','2': ' Flats'},brand: {'1': 'Fits'}}

const queryParams = Object.entries(activeFilters).map((query) => {
  //Join all query keys values with ','
  const values = Object.keys(query[1]).map((val) => val).join(',');
  //add these values to name of the query
  return query[0]+'='+values;
}).join('&'); //join final result with '&'

console.log(queryParams)
url = 'https://google.com?'+queryParams;
console.log(url)

我将使用 qs 包将数据字符串化为 URL 查询参数。但首先,我们需要像下面这样转换数据:

qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' })
// 'a=b,c'

可以通过将 encode 选项设置为 false 来禁用编码。

例如

var qs = require("qs")

const activeFilters =  {
    category: {
        '1': 'View All',
        '2': ' Flats'
    },
    brand: {
        '1': 'Fits'
    }
}

const r = Object.keys(activeFilters).reduce((acc, cur) => {
  acc[cur] = Object.keys(activeFilters[cur]);
  return acc;
}, {})

const search = qs.stringify(r, {arrayFormat: 'comma', encode: false})
console.log(search)
// "category=1,2&brand=1"
console.log(`https://api.websiteurl.com/products?${search}`) 
// "https://api.websiteurl.com/products?category=1,2&brand=1"

RunKit

我会这样做:

const objectToParams = (object) => {
  if (object && Object.keys(object).length > 0) {
    const resultArr = [];
    Object.keys(object).map((key) => {
      const keys = Object.keys(object[key]).join(",");
      resultArr.push(`${key}=${keys}`);
    });
    return resultArr.join("&");
  }
};

const activeFilters = {
    category: {
        '1': 'View All',
        '2': ' Flats'
    },
    brand: {
        '1': 'Fits'
    }
}

const url = `https:google.com/products?`;
const result = `${url}${encodeURIComponent(objectToParams(activeFilters))}`;

console.log("url is: ", result)