简体   繁体   English

Javascript 将 Object 转换为 URL

[英]Javascript Convert an Object to a URL

I have an object which looks something like this:我有一个看起来像这样的 object:

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

I want to map through the object and use these as URL parameters.我想通过 object map 并将这些用作 URL 参数。 The end result will look something like this:最终结果将如下所示:

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

I am using react and I can use lodash.我正在使用反应,我可以使用 lodash。 Wanted help on whats the best way to achieve this想要帮助了解实现这一目标的最佳方法

You can make use of Object.entries and map to achieve the desired result您可以使用Object.entriesmap来实现所需的结果

 const filters = { activeFilters: { category: { "1": "View All", "2": " Flats", }, brand: { "1": "Fits", }, }, }; const path = Object.entries(filters.activeFilters).map(([k, v]) => `${k}=${Object.keys(v)}`).join("&"); const url = "https://api.websiteurl.com/products"; const result = `${url}?${path}`; console.log(result);

I would do like this:我会这样做:

 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)

 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)

I will use qs package to stringify the data to url query parameters.我将使用qs package 将数据字符串化为 url 查询参数。 But first, we need to convert the data.但首先,我们需要转换数据。

Eg例如

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)
console.log(`https://api.websiteurl.com/products?${search}`)

RunKit运行套件

Use the URL object:使用URL object:

 const filters = { activeFilters: { category: { "1": "View All", "2": "Flats" }, brand: { "1": "Fits" } } }; let u = new URL("https://api.websiteurl.com/products"); Object.entries(filters.activeFilters).forEach(function([key, value]) { u.searchParams.append(key, Object.keys(value).join(",")); }); console.log(u.href);

The , should be encoded as %2C according to the specs . ,应根据规范编码为%2C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM