I have an object of the following type:
const obj = [
{
id:1,
name:'Admin',
new: [{text:'text', count:4}],
old: [],
ongoing: [{text: 'text1', count:5}]
}
]
I need to get array with objects if they exist in new, old, ongoing object properties
expected result
[
{
"id": 1,
"level": "new",
"text": "text" ,
"count": 4,
},
{
"id": 1,
"level": "ongoing",
"text": "text1" ,
"count": 5,
},
]
That is, if arrays of objects are available in the object using the keys new, ongoing, old, I create for each object and add to the array, if the key is empty, then I skip
My solution
let data = []
guidance.map((guidanceEntity) => {
guidanceEntity?.new?.sort((a, b) => b.count - a.count).slice(0, 1)
.map(guidanceItem => {
data.push(
{
id: guidanceEntity.id,
level: 'new',
text: guidanceItem.text,
count: guidanceItem.count,
},
)
})
guidanceEntity?.ongoing?.sort((a, b) => b.count - a.count).slice(0, 1)
.map(guidanceItem => {
data.push({
id: guidanceEntity.id,
level: 'ongoing',
text: guidanceItem.text,
count: guidanceItem.count,
})
})
guidanceEntity?.old?.sort((a, b) => b.count - a.count).slice(0, 1)
.map(guidanceItem => {
data.push({
id: guidanceEntity.id,
level: 'old',
text: guidanceItem.text,
count: guidanceItem.count,
})
})
})
const obj = [ { ... } ]; it looks like you have an array of objects, not an object; can you confirm, please?guidanceEntity?.new?.sort((a, b) => b.count - a.count).slice(0, 1).map(guidanceItem => { ... }does not make a lot of sense; if you want just the first item, you can simply select it withguidanceEntity?.new?.sort((a, b) => b.count - a.count)[0]then, if you have a single item, it makes non sense to usemap(the same goes forongoingandold)