admin管理员组

文章数量:1401367

I need to extract filter which is an array of objects from a URL string:

http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u.

This is currently what I have:

  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const filterParamsValue = searchParams.getAll('filter'); // returns []

This is what I want to get from the filter:

[ { id: 'MenuID', value: '2' }, { id: 'ParentMenuName', value: 'u' } ]

I need to extract filter which is an array of objects from a URL string:

http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u.

This is currently what I have:

  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const filterParamsValue = searchParams.getAll('filter'); // returns []

This is what I want to get from the filter:

[ { id: 'MenuID', value: '2' }, { id: 'ParentMenuName', value: 'u' } ]
Share Improve this question asked Aug 10, 2021 at 9:48 Micko MagallanesMicko Magallanes 2702 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Some quick functioning :D ...

let s = `http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u`

// get just array of strings like ['filter[0][id]=MenuID', ...]
let arr = s.split(/\&/).slice(1)
let filters = {}

arr.forEach(f => {
    const id = f.match(/\[([\d]+)\]/)[1]
    const prop = f.match(/\[([a-z]+)\]/)[1]

    if(filters[id]) {
        filters[id][prop] = f.match(/=([\w]+)/)[1]
    } else {
        filters[id] = {}
        filters[id][prop] = f.match(/=([\w]+)/)[1]
    }
})


// show filters object:
console.dir( filters )

/*

  { 
    0: { id: "MenuID", value: "2"},
    1: { id: "ParentMenuName", value: "u"}
  }

*/

This gives you Object of filters. If you need an array, you may convert it as:

/**
 * get object of filters and make an array of filters 
 */
const arrayOfFilters = []

for(key in filters) {
    arrayOfFilters.push(filters[key])
}

console.log(arrayOfFilters)

A short version

function getSearchParameters () {
    const url = new URL(window.location)
    const searchParams = new URLSearchParams(url.search)
    const paramObj = {}
    for (const key of searchParams.keys()) {
        paramObj[key] = searchParams.getAll(key).length > 1
            ? searchParams.getAll(key)
            : searchParams.get(key)
    }
    return paramObj
}

I wrote a prototype function to parse square brackets array of objects. This function is dynamically parse brackets, that is good for nested objects

URLSearchParams.prototype.toObject = function () {
    let _obj = {};
    const bracketToDots = function (str) {
        return str.replaceAll('[', '.').replaceAll(']', '')
    }
    const parseDotNotation = function (str, val, obj) {
        let currentObj = obj,
            keys = str.split("."),
            i, l = Math.max(1, keys.length - 1),
            key;

        if (l === 1) {
            key = keys[0];
            currentObj[key] = val;
        } else {
            for (i = 0; i < l; ++i) {
                key = keys[i];
                currentObj[key] = currentObj[key] || {};
                currentObj = currentObj[key];
            }

            currentObj[keys[i]] = val;
        }
    }
    for (const [key, value] of this.entries()) {
        parseDotNotation(bracketToDots(key), value, _obj);
    }
    return _obj;
}

const lo = new URL('http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u');
const searchParams = new URLSearchParams(lo.search);
const params = searchParams.toObject();

console.log(params['filter'])

Result:

{
  "0": {
    "id": "MenuID",
    "value": "2"
  },
  "1": {
    "id": "ParentMenuName",
    "value": "u"
  }
}

本文标签: javascriptGet array of objects from URLSearchParamsStack Overflow