Rizky Tahara Shita
Rizky Tahara Shita

Reputation: 5

Nested Array to Query Params for Filters in Searching

I have:

[
    {
        id: // the field to be search
            {
                eq: '1234'  // eq is the operand; 1234 is the keyword
            }
    },
    {
        description:
            {
                like: 'desc'
            }
    }
]

How to transform it (in Ember.JS) to query parameters to:

?filter[id][eq]=1234&filter[description][like]=desc

since the API needed the format like so for the filters?

Upvotes: 0

Views: 3251

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

In ES6 way.

var arr = [
    {
        id: 
            {
                eq: '1234'
            }
    },
    {
        description:
            {
                like: 'desc'
            }
    }
];


const url = '?' + arr.map(filter => {
  // assuming single key, so using pop(). 
  // Change accordingly if your input array schema changes.
  const major = Object.keys(filter).pop();
  const minor = Object.keys(filter[major]).pop();
  return `filter[${major}][${minor}]=${filter[major][minor]}`;
}).join('&');

console.log(url);
// output: ?filter[id][eq]=1234&filter[description][like]=desc

Upvotes: 0

Hoang Subin
Hoang Subin

Reputation: 7400

The solution is very simple. because the first element and second element are different, So I assume that it is always like that.

Here is solution:

const data = [
    {
        id:{
            eq: '1234'
        }
    },
    {
        description:{
            like: 'desc'
        }
    }
];

const [ first, second ] = data;

const queryParams = `?filter[id][eq]=${first['id']['eq']}&filter[description][like]=${second['description']['like']}`;
console.log(queryParams);

Then the output will be:

?filter[id][eq]=1234&filter[description][like]=desc

Upvotes: 0

Tân
Tân

Reputation: 1

Maybe this is what you are looking for:

var filter = [
    {
        id: 
            {
                eq: '1234'
            }
    },
    {
        description:
            {
                like: 'desc'
            }
    }
];

var output = '?';

filter.forEach(function (item) {
  output += 'filter';

  Object.keys(item).forEach(function (prop) {
    output += '[' + prop + ']';
  
    Object.keys(item[prop]).forEach(function (subProp) { 
      output += '[' + subProp + ']=' + item[prop][subProp]; 
    });
  });
  
  output += '&';
});

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

console.log(output);

You can make a loop through the array and use Object.key() with forEach function to get the property name and value.

Upvotes: 1

Related Questions