-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
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
JSking
  • 399
  • 1
  • 4
  • 18

2 Answers2

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);
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • Worth noting that even using Object,entries() the *first* may not always be the same property key. Whole thing seems like an XY problem – charlietfl Nov 03 '19 at 08:36
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)];
danikaze
  • 1,550
  • 2
  • 16
  • 34