I have object like this. I getting this object on backend with query and then transform with qs string library.
{
color: 'red,white',
size: 'xl',
manufacturer: 'adidas,nike'
}
I would like have array of object, what i need for prisma map filtering
const filterList = [
{filter: "color", value: "red"},
{filter: "color", value: "white"},
{filter: "size", value: "xl"},
{filter: "manufacturer", value: "adidas"},
{filter: "manufacturer", value: "nike"},
];
How can i this handle ? Thanks for a reply
CodePudding user response:
To create the desired array of objects from the original object, you can use the Object.entries()
method to get an array of key-value pairs, then use Array.map()
to iterate over the key-value pairs and create the array of objects.
Here is an example:
const obj = {
color: 'red,white',
size: 'xl',
manufacturer: 'adidas,nike'
};
const filterList = Object.entries(obj).map(([filter, value]) => {
return value.split(",").map(v => ({ filter, value: v }));
}).flat();
console.log(filterList);
This will output the following array:
[
{filter: "color", value: "red"},
{filter: "color", value: "white"},
{filter: "size", value: "xl"},
{filter: "manufacturer", value: "adidas"},
{filter: "manufacturer", value: "nike"},
]
CodePudding user response:
Something like that would do it :
const data = {
color: "red,white",
size: "xl",
manufacturer: "adidas,nike",
};
const result = [];
// color
let str = data.color.split(",");
str.forEach((element, index) => {
result.push({ filter: "color", value: str[index] });
});
console.log(result);
And do the same for size and manufacturer.
CodePudding user response:
Like this?
function transform(filters) {
return Object.entries(filters).reduce((acc, [filter, commaSeparatedValues]) => {
commaSeparatedValues.split(",").forEach(value => {
acc.push({
filter,
value
})
});
return acc;
}, [])
}
const sample = {
color: "red,white",
size: "xl",
manufacturer: "adidas,nike",
};
const transformed = transform(sample);
console.log(transformed);