2

I have an object which looks something like this:

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

I want to map through the object and use these as URL parameters. 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. Wanted help on whats the best way to achieve this

6
  • You don't need lodash nor React for that. Commented Nov 29, 2021 at 8:20
  • Are category and brand really object values and not Arrays? It's unusual to have numeric property keys in object values. Commented Nov 29, 2021 at 8:21
  • https://api.websiteurl.com/products&category=1,2&brand=1 <-- This is an invalid URI, you're missing the querystring ? character. Commented Nov 29, 2021 at 8:21
  • I know, I wanted to let everyone know what I am using and If we can produce a more readable and easy solution then it would be best Commented Nov 29, 2021 at 8:21
  • @Dai yes it's a redux object where keys represent the ids. I update it using something like this: {...state.filters, [action.id]: [action.name]} Commented Nov 29, 2021 at 8:37

4 Answers 4

1

You can make use of Object.entries and map to achieve the desired result

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

Sign up to request clarification or add additional context in comments.

9 Comments

Don't forget to encode the querystring parameters, otherwise a value with = or & in it will break everything.
Ideally you should encodeURIComponent the values although in this example they are just numbers.
Also your code is also missing the ? character.
Your code doesn't include filters.brand btw.
You're using encodeURIComponent incorrectly. You need to use encodeURIComponent to encode each querystring name and value separately. But you shouldn't need to use encodeURIComponent if you use URLSearchParams instead.
|
0

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)

Comments

0

I will use qs package to stringify the data to URL query parameters. But first, we need to convert the data like below:

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

The encoding can be disabled by setting the encode option to false.

E.g.

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

1 Comment

What does qs do that the built-in URLSearchParams object doesn't? I don't think we should be perpetuating the JS package mess situation we're in right now: in-box solutions should be preferred imo.
0

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)

4 Comments

You aren't URI-encoding parameter names and values. You're missing the ? separator.
added ? operator.
Thank you @Dai. Added URI-encoding as well.
You're using encodeURIComponent incorrectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.