-2

I want to include the error associated with the field 'firstname' but I can't figure out how to reference the correct branch of the JSON-encoded object.

{ 
"_original":{ 
"firstname":"1",
"lastname":"1",
"email":"1@1.com",
"password":"1"
},
"details":[ 
  { 
    "message":"\"firstname\" length must be at least 3 characters long",
    "path":[ 
    "firstname"
    ],
    "type":"string.min",
    "context":{ 
      "limit":3,
      "value":"1",
      "label":"firstname",
      "key":"firstname"
    }
},
{ 
"message":"\"lastname\" length must be at least 3 characters long",
"path":[ 
"lastname"
],
"type":"string.min",
"context":{ 
"limit":3,
"value":"1",
"label":"lastname",
"key":"lastname"
}
}
]
}

How do I return the indented object in the details array? I am searching on path:["firstname"]

Teymour
  • 1,832
  • 1
  • 13
  • 34
Rob
  • 1,297
  • 2
  • 16
  • 30

2 Answers2

2

Can you try the below code

function getErrorMessage(json, key) {
    return a.details.find(d => d.path.includes(key));
}

var a = { 
"_original":{ 
"firstname":"1",
"lastname":"1",
"email":"1@1.com",
"password":"1"
},
"details":[ 
  { 
    "message":"\"firstname\" length must be at least 3 characters long",
    "path":[ 
    "firstname"
    ],
    "type":"string.min",
    "context":{ 
      "limit":3,
      "value":"1",
      "label":"firstname",
      "key":"firstname"
    }
},
{ 
"message":"\"lastname\" length must be at least 3 characters long",
"path":[ 
"lastname"
],
"type":"string.min",
"context":{ 
"limit":3,
"value":"1",
"label":"lastname",
"key":"lastname"
}
}
]
};

console.log(getErrorMessage(a, 'firstname'));
Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17
0

Assuming you've parsed it and so it's not JSON anymore, you'd search the details array for path[0] === "firstname", like this (if you're referencing that with data):

const entry = data.details.find(({path}) => path[0] === "firstname");

Live Example:

const data = {
 "_original": {
  "firstname": "1",
  "lastname": "1",
  "email": "1@1.com",
  "password": "1"
 },
 "details": [{
   "message": "\"firstname\" length must be at least 3 characters long",
   "path": [
    "firstname"
   ],
   "type": "string.min",
   "context": {
    "limit": 3,
    "value": "1",
    "label": "firstname",
    "key": "firstname"
   }
  },
  {
   "message": "\"lastname\" length must be at least 3 characters long",
   "path": [
    "lastname"
   ],
   "type": "string.min",
   "context": {
    "limit": 3,
    "value": "1",
    "label": "lastname",
    "key": "lastname"
   }
  }
 ]
};

const entry = data.details.find(({path}) => path[0] === "firstname");
console.log(entry);
.as-console-wrapper {
    max-height: 100% !important;
}

(Adjust the contents of the find operation as necessary.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875