Reputation: 235
I have a filter component which user can choose any data to filter so I store this data in state.when I want to create a params for query some of the field not choosen by user I only wanna get the one which has value here is the code ;
function createParams(params = {}) {
let result = "?";
for (let key in params) {
result += `${key}=${params[key]}&`;
}
return result;
}
export async function callApi(params) {
const parameters = createParams(params);
try {
const response = await fetch(URL+ parameters);
const res = await response.json();
return res;
} catch (error) {
console.error(error)
throw error;
}
}
export const requestProperties = (params) => callApi(params);
const requestedParams = {type:"Fiat", model:"500", color:""};
I only want to get the type and model because it has been choosen by user to filter. I dont wanna include the colour
Thank you..:)
Upvotes: 2
Views: 52
Reputation: 29282
You can destructure the object if you only want to exclude one key-value pair
const requestedParams = {type:"Fiat", model:"500", color:""};
const exclude = 'color';
const {[exclude]: remove, ...rest} = requestedParams;
console.log(rest);
If you have multiple key-value pairs that you want to exclude, you can use reduce function
const requestedParams = { type: "Fiat", model: "500", color: "" };
const res = Object.entries(requestedParams).reduce((acc, curr) => {
return curr[1] ? (acc[curr[0]] = curr[1], acc) : acc;
}, {});
console.log(res);
Upvotes: 2
Reputation: 5308
You can take entries
and then filter out the records.
var requestedParams = {type:"Fiat", model:"500", color:""};
var result = Object.fromEntries(Object.entries(requestedParams).filter(([k,v])=>v));
console.log(result);
Upvotes: 2