Home > database >  How to get the value of a certain key of a nested JSON object (2nd level and in general)?
How to get the value of a certain key of a nested JSON object (2nd level and in general)?

Time:08-18

I have a nested JSON Object called "data".

console.log(Object.values(data['Meta']['Symbol']));

That gives me every single letter/character of the value:

Array(3) [ "S", "A", "P" ]

What I want, is the whole String: "SAP" Where is the mistake?

Things I have tried:

That gives me the whole array (including "SAP") but I just want the String i.e. value "SAP":

console.log(Object.values(data['Meta']

That gives me an empty array (of three elements):

console.log(Object.keys(data['Meta']['Symbol']));

Information that I was looking for on the internet, doesn't adress this issue.

Structure of the JSON object:

{
    "Meta": {
        "Symbol": "SAP"
    }
}

CodePudding user response:

Firstly, this is not JSON; JSON is a string. Next, if you want to turn an array into a string, use array.join("");

console.log(data['Meta']['Symbol'].join(""));

CodePudding user response:

If the JSON object is

{
    "Meta": {
       "Symbol": "SAP"
    }
}

And you import it with let data = JSON.parse("MY JSON") Then it's just console.log(data.Meta.Symbol)

CodePudding user response:

Why

const data = { Meta: { Symbol: 'SAP' } };

/**
 * 1. String is an object;
 * 2. Using the Objects.prototype.values method will return an array of all the values (e.g. All the characters in the String.);
 * 
 * MDN documentation
 * ------------------------------------------------------
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
 * ------------------------------------------------------
 */
console.log(Object.values(data['Meta']['Symbol']));

Output

[ 'S', 'A', 'P' ]

How

const data = { Meta: { Symbol: 'SAP' } };

/**
 * To retrieve the value of the string, you must access it using the dot notation or bracket notation.
 *
 * Dot notation: data.Meta.Symbol
 * Bracket notation: data['Meta']['Symbol']
 *
 * MDN documentation
 * ------------------------------------------------------
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
 * ------------------------------------------------------
 */
console.log(data['Meta']['Symbol']);

Output

SAP
  • Related