
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Get value for key from nested JSON object in JavaScript
Suppose, we have a nested JSON object like this −
const obj = { "prop": [ { "key": "FOO", "value": "Foo is wonderfull, foo is great" }, { "key": "BAR", "value": "Bar is bad, really bad" } ] };
We are required to write a JavaScript function that takes in one such object as the first argument, and a key string as the second argument.
Our function should then return the value for the "value" property to which that particular key property belongs.
Example
The code for this will be −
const obj = { "prop": [ { "key": "FOO", "value": "Foo is wonderfull, foo is great" }, { "key": "BAR", "value": "Bar is bad, really bad" } ] }; const findByKey = (obj, key) => { const arr = obj['prop']; if(arr.length){ const result = arr.filter(el => { return el['key'] === key; }); if(result && result.length){ return result[0].value; } else{ return ''; } } } console.log(findByKey(obj, 'BAR'));
Output
And the output in the console will be −
Bar is bad, really bad
- Related Articles
- Extract key value from a nested object in JavaScript?
- Test for existence of nested JavaScript object key in JavaScript
- Print JSON nested object in JavaScript?
- Get key from value in JavaScript
- Constructing a nested JSON object in JavaScript
- Create nested JSON object in PHP?
- Changing value of nested object keys in JavaScript
- JavaScript: How to Create an Object from Key-Value Pairs
- How to only get the data of the nested JSON object in MongoDB?
- Create array from JSON object JavaScript
- From JSON object to an array in JavaScript
- Removing property from a JSON object in JavaScript
- Get key from value in Dictionary in Python
- JavaScript - Sort key value pair object based on value?
- Creating a JavaScript Object from Single Array and Defining the Key Value?

Advertisements