Home > database >  How to get all the values of a key in a nested JavaScript object?
How to get all the values of a key in a nested JavaScript object?

Time:01-18

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."
]

CodePudding user response:

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)

  • Related