0

I'm using jQuery and I have following dynamical filter data and want it to transform in url params.

customFilter = [];

if(filterDateFrom !== 'Invalid date') {
     customFilter.push({
                    property: 'createdAt',
                    dir: 'next',
                    value: '2020-05-01'
     });
}

if(filterDateTo !== 'Invalid date') {
    customFilter.push({
                    property: 'createdAt',
                    dir: 'back', 
                    value: '2020-05-12'
    });
}

The result of params should look like this:

customFilter[0][property]=createdAt&customFilter[0][dir]=next&customFilter[0][value]=2020-05-01&customFilter[1][property]=createdAt&customFilter[1][dir]=back&customFilter[1][value]=2020-05-12

My attempts with jQuery's $.param did not work. Does anyone have an idea?

0

2 Answers 2

1

Is that what you are looking for:

var output = "";

var customFilter  = [{'property': 'createdAt', 'dir': 'next', 'value': '2020-05-01'},
             {'property': 'createdAt', 'dir': 'next', 'value': '2020-05-01'},
             {'property': 'createdAt', 'dir': 'next', 'value': '2020-05-01'}
            ];


for(var i = 0; i < customFilter.length; i++){
    output = output + 'customFilter' + '[' + i + ']' + '[property]='+ customFilter[i].property + '&' + 'customFilter' + '[' + i + ']' + '[property]='+ customFilter[i].dir + '&' + 'customFilter' + '[' + i + ']' + '[property]='+ customFilter[i].value + '&'
}

output = output.substring(0, output.length-1);
console.log(output);

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

1 Comment

thanks for your answer! I had speculated on a solution similar to $.param, which would automatically and dynamically read the objects within the array. the properties are not firmly defined and can change ... I have now modified it as in the answer below.
0

The properties are not fixed and can change ... I have now modified it so that properties of objects are read dynamically:

output = "";

var customFilter  = [
        {'property': 'createdAt', 'dir': 'next', 'value': '2020-05-01'},
        {'property': 'createdAt', 'operator': '<=', 'value': '2020-05-01'},
        {'property': 'editedAt', 'dir': 'next', 'value': '2020-05-01'}
    ];


for(var i = 0; i < customFilter.length; i++){
    for (let [property, value] of Object.entries(customFilter[i])) {
        output+= '&customFilter' + '[' + i + ']' + '[' + property + ']=' + encodeURIComponent( value );
    } 
}

console.log(output);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.