-3

Here is my JSON object

{
    "errors": {
        "product_name": {
            "message": "Product name is required",
            "name": "ValidatorError"
        },
        "category": {
            "message": "Category is required",
            "name": "ValidatorError"

        }
    }
}

My aim is to access the first "message", though it can be access via

 errors.product_name.message

this is not the goal, my goes is to get first message without using the "product_name" object, like

errors[0].message
1
  • 1
    there is no array in what you've shown Commented Nov 3, 2019 at 8:31

2 Answers 2

1

Use Object.entries to iterate on the errors and fetch the message property

const obj = {
	"errors": {
		"product_name": {
			"message": "Product name is required",
			"name": "ValidatorError"
		},
		"category": {
			"message": "Category is required",
			"name": "ValidatorError"

		}
	}
};

const [,value] = Object.entries(obj.errors)[0];
console.log(value.message);

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

1 Comment

Worth noting that even using Object,entries() the first may not always be the same property key. Whole thing seems like an XY problem
0

First you need to know, an object is not a Set. The order is not always the same (it depends on the iterator implementation).

It usually gives you the order of the declaration keys but it doesn't need to be true.

Then, some ways to get what you want.

With Object.keys:

const keys = Object.keys(obj.errors);
const firstError = obj.errors[keys[0]];

With Object.entries:

const entries = Object.entries(obj.errors);
const firstError = entries[0][1];

Then, if you don't need all the keys you can just stop at the first one:

function getFirstKey(obj) {
  for (const k in obj) {
    return k;
  }
}

const firstError = obj.errors[getFirstKey(obj.errors)];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.