console.log(value)
{
List: [
{
id: 1
title: 'hi',
content: [
{
id: 1,
functionId: 11,
}
]
}
{
id: 2,
title: 'minsu',
content: []
}
]
}
I want to delete the object if there is no content array.
I am creating a variable called control and outputting it using the map function inside. If the objects without content array have to be deleted by applying a filter condition, I don't know how to do it.
let control: any[any] = [
value.map((value: any) => {
return {
id: value?.id,
title: value?.title,
content: value?.content[0].functionId
}
})
]
But now, when I do console.log(control), an error occurs because the second object does not have content.
I want to delete the second object without content and print it like this.
console.log(control)
[
id: 1,
title: 'hi',
functionId: 11
]
CodePudding user response:
First filter
out the elements with 0 length content array or content array doesn't exists and then map
to transform it
const List = [ { id: 1, title: 'hi', content: [ { id: 1, functionId: 11, } ] }, { id: 2, title: 'minsu', content: [] } ]
const control = List
.filter(({content}) => content?.length)
.map(({id,title,content:[{functionId}]}) => ({id,title,functionId}))
console.log(control)
CodePudding user response:
Filter source list the way you need and reapply filtered list as new value
const sourceObject = {
list: [
{
id: 1,
title: 'hi',
content: [
{
id: 1,
functionId: 11,
}
]
},
{
id: 2,
title: 'minsu',
content: []
}
]
};
const filteredList = sourceObject.list.filter(element => (
typeof(element.content) === 'object' && element.content.length > 0
));
sourceObject.list = filteredList;
console.log(sourceObject);
CodePudding user response:
I usually use reduce
to solve problems like this
const items = [
{
id: 1,
title: 'hi',
content: [
{
id: 1,
functionId: 11,
}
]
},
{
id: 2,
title: 'minsu',
content: []
}
];
const result = items.reduce((rs, item) => {
const functionId = item?.content?.[0]?.functionId;
if (functionId) {
rs.push({
id: item.id,
title: item.title,
functionId
})
}
return rs;
}, [])
console.log(result)