I'm trying to deconstruct this object to get "Swiss franc", assuming i don't know the key CHF.
currencies = {CHF: {name: "Swiss franc", symbol: "Fr."}}
My attempts:
Object.values(Object.values(currencies)[0]
// -> Swiss franc,Fr.
Object.values(Object.values(currencies)[0].name
// -> S,w,i,s,s, ,f,r,a,n,c
// why does it split the string?? not retrieve the value based on key name??
// i know how to join the strings back, but i'm confused why is this result?)
CodePudding user response:
just a little modification to your code:
const currencies = {CHF: {name: "Swiss franc", symbol: "Fr."}}
console.log(Object.values(Object.values(currencies)[0])[0])
// OR Simply
console.log(Object.values(currencies)[0].name)
CodePudding user response:
currencies = {CHF: {name: "Swiss franc", symbol: "Fr."}}
This will do it,
Object.values(currencies)[0].name
Breakdown :-
Object.values(currencies)
gives [{name: "Swiss franc", symbol: "Fr."}]
Object.values(currencies)[0]
gives {name: "Swiss franc", symbol: "Fr."}
Object.values(currencies)[0].name
gives Swiss franc.
CodePudding user response:
Object.entries
Implementation Reference
Explanation
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well.
Working Example
const currencies = { CHF: { name: "Swiss franc", symbol: "Fr.", }}
console.log(Object.entries(currencies)[0][1].name);
Code Explanation
Object.entries(currencies)
The above statement return an array as below
[["CHF", {symbol: 'Fr.', name: 'Swiss franc'}]]
An array of combination of key value pairs in the object.
We are interested in the node zero of the array and index one of the first node of array.
So it will be
Object.entries(currencies)[0][1].name
Object.values
implementation. Reference.
Explanation
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)
Working Example
const currencies = { CHF: { name: "Swiss franc", symbol: "Fr.", }}
console.log(Object.values(currencies)[0].name);
Code Explanation
Object.values(currencies)
Tie above expression will return the array of values. Since we have only one key, the output of above statement will be
[{ symbol: 'Fr.', name: 'Swiss franc' }]
So the requird node will be
Object.values(currencies)[0].name