0

I'm developing a backend using NodeJS and ExpressJS, and using MongoDB to store data.
While testing the backend, I am getting a JSON object (which I've converted in JavaScript here) as you can see below.

const errors = {
    username: {
        name: "ValidatorError",
        message: "Username must contain at least 3 characters.",
        kind: "minlength",
        path: "username",
        value: "a"
    },
    name: {
        name: "ValidatorError",
        message: "Name must contain at least 3 characters.",
        kind: "minlength",
        path: "name",
        value: "A"
    },
    email: {
        name: "ValidatorError",
        message: "Email is not valid.",
        kind: "regexp",
        path: "email",
        value: "a"
    },
    password: {
        name: "ValidatorError",
        message: "Password must contain at least 8 characters.",
        kind: "minlength",
        path: "password",
        value: "a"
    }
}

I want value of all the message keys present in the given object in form of a JavaScript array.
How to do it?

For more clarity, here is the output which I'm expecting:

const arrayName = [
    "Username must contain at least 3 characters.",
    "Name must contain at least 3 characters.",
    "Email is not valid.",
    "Password must contain at least 3 characters."
]

1 Answer 1

3

You can use Object.values and a map like this:

const errors = {
    username: {
        name: "ValidatorError",
        message: "Username must contain at least 3 characters.",
        kind: "minlength",
        path: "username",
        value: "a"
    },
    name: {
        name: "ValidatorError",
        message: "Name must contain at least 3 characters.",
        kind: "minlength",
        path: "name",
        value: "A"
    },
    email: {
        name: "ValidatorError",
        message: "Email is not valid.",
        kind: "regexp",
        path: "email",
        value: "a"
    },
    password: {
        name: "ValidatorError",
        message: "Password must contain at least 8 characters.",
        kind: "minlength",
        path: "password",
        value: "a"
    }
}

const messages = Object.values(errors).map(err => err.message);

console.log(messages)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.