I have a very strange issue, and I'm not able to fix it. I have this Json response from an API:
{
"type::new":"#000000",
"type::closed":"#000011",
"priority::low":"#FFFFFF",
"priority::normal":"#FF0000",
"priority::high":"#FFFF00",
"type::bug":"#001100"
}
I need to get, for example, only key that start with "type", so:
"type::new", "type::closed", "type::bug"
and assign each element to an array object with these values:
items: [
{
id: 'type::new',
value: 'type::new',
title: 'type::new'
},
{
id: 'type::closed',
value: 'type::closed',
title: 'type::closed'
},
{
id: 'type::bug',
value: 'type::bug',
title: 'type::bug'
}
]
I'm in a Svelte script, I tryed this but it not works (and I'm stopping only on get without filter them) [response is a result of fetch API):
const data = await response.json();
return data.map((item: any) => ({ id: item.key(), value: item.key(), title: item.key()}));
Thank you so much :)
CodePudding user response:
As stated in my comment, you can't map()
objects properties, but you can loop them over using Object.keys()
or for...in
.
const data = {
"type::new": "#000000",
"type::closed": "#000011",
"priority::low": "#FFFFFF",
"priority::normal": "#FF0000",
"priority::high": "#FFFF00",
"type::bug": "#001100"
}
//
// USING for...in
//
const results = []
for (let key in data) {
if (key.includes('type::')) {
results.push({ id: key, value: key, title: key })
}
}
console.log(results)
//
// USING Object.keys(), filter() AND map()
//
const results2 = Object.keys(data).filter(item => item.includes('type::')).map(key => {
return { id: key, value: key, title: key }
})
console.log(results2)