我有以下类型的对象:
const obj = [
{
id:1,
name:'Admin',
new: [{text:'text', count:4}],
old: [],
ongoing: [{text: 'text1', count:5}]
}
]
如果对象存在于new
, old
,ongoing
对象属性中,我需要获取包含对象的数组
预期结果
[
{
"id": 1,
"level": "new",
"text": "text" ,
"count": 4,
},
{
"id": 1,
"level": "ongoing",
"text": "text1" ,
"count": 5,
},
]
也就是说,如果对象数组在对象中使用新的、正在进行的、旧的键可用,我为每个对象创建并添加到数组中,如果键为空,那么我跳过
我的解决方案
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 = {
id: 1,
name: 'Admin',
new: [{
text: 'text',
count: 4
}],
old: [],
ongoing: [{
text: 'text1',
count: 5
}]
}
const targetKeys = ['new', 'old', 'ongoing']
const transform = o => targetKeys.reduce((acc, curr) => acc.concat(o[curr].length ? {
id: o.id,
level: curr,
text: o[curr][0].text,
count: o[curr][0].count
} : []), [])
console.log(transform(obj))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句