在 ES6 中组合嵌套数组
Combine Nested Array in ES6
我需要合并显示validationMessages
。它们是嵌套的,如何组合?
const errors = [
{
"id": "101_1.jpeg",
"imageValidationMessages": [
{
"attribute": "test",
"validationMessages": [
"Error message 1"
]
}
]
}
]
const errorMessages =
errors?.length &&
errors?.imageValidationMessages?.flatMap(
(o) => o.validationMessages
)
console.log(errorMessages)
你可以这样做
const errorMessages =
errors?.length &&
errors?.flatMap((err => err.imageValidationMessages?.flatMap(
(o) => o.validationMessages
)))
const errors = [
{
"id": "101_1.jpeg",
"imageValidationMessages": [
{
"attribute": "test",
"validationMessages": [
"Error message 1"
]
}
]
}
]
let arr=errors.map(e=>e.imageValidationMessages.map(p=>p.validationMessages)).flat(2)
console.log(arr)
const errors = [
{
"id": "101_1.jpeg",
"imageValidationMessages": [
{
"attribute": "test",
"validationMessages": [
"Error message 1"
]
}
]
}
]
let arr=errors.flatMap(e=>e.imageValidationMessages.flatMap(p=>p.validationMessages))
console.log(arr)
我需要合并显示validationMessages
。它们是嵌套的,如何组合?
const errors = [
{
"id": "101_1.jpeg",
"imageValidationMessages": [
{
"attribute": "test",
"validationMessages": [
"Error message 1"
]
}
]
}
]
const errorMessages =
errors?.length &&
errors?.imageValidationMessages?.flatMap(
(o) => o.validationMessages
)
console.log(errorMessages)
你可以这样做
const errorMessages =
errors?.length &&
errors?.flatMap((err => err.imageValidationMessages?.flatMap(
(o) => o.validationMessages
)))
const errors = [
{
"id": "101_1.jpeg",
"imageValidationMessages": [
{
"attribute": "test",
"validationMessages": [
"Error message 1"
]
}
]
}
]
let arr=errors.map(e=>e.imageValidationMessages.map(p=>p.validationMessages)).flat(2)
console.log(arr)
const errors = [
{
"id": "101_1.jpeg",
"imageValidationMessages": [
{
"attribute": "test",
"validationMessages": [
"Error message 1"
]
}
]
}
]
let arr=errors.flatMap(e=>e.imageValidationMessages.flatMap(p=>p.validationMessages))
console.log(arr)