_mercury – 19-03 Jul 23

I have an array of objects like above ... suppose it has many objs So how to get the object with abbreviation en-US ? from the array by array accessing ? labels['en-US]` seems not to work .. it should be one line because i use it in EJS view engine
S
ScriptyChris633d ago
Like this?
.filter(({ abbreviation }) => abbreviation === 'en-US')
.filter(({ abbreviation }) => abbreviation === 'en-US')
M
_mercury633d ago
mmm Ok thx , i think i should remap the array of objs
UU
Unknown User633d ago
M
_mercury633d ago
yes
M
_mercury633d ago
so how i convert this to an array to get the label by locals[abbreviation]
M
_mercury633d ago
to be easy to access @ScriptyChris
S
ScriptyChris633d ago
Use .find() instead of .filter() so it will give you first object, which has 'en-US' as abbreviation and then you can use object.abbreviation
M
_mercury633d ago
I am thinking of restructure the obove obj
S
ScriptyChris633d ago
What do you mean?
M
_mercury633d ago
const attr_lbs_remapped = [];
attr_labels.map((label) => {
return (attr_lbs_remapped[label.abbreviation] = label.label);
});
const attr_lbs_remapped = [];
attr_labels.map((label) => {
return (attr_lbs_remapped[label.abbreviation] = label.label);
});
This does not work You may understand what i mean from the code Instead of array of objs It should be easy to be associative array ? Key : abbreviation, value : label
S
ScriptyChris633d ago
I don't have idea what are you trying to do 🤔 What structure do you want to have as an output?
M
_mercury633d ago
thx for your active help I did it
const remapped_labels = {};
attr_labels.forEach((label) => {
remapped_labels[label.abbreviation] = label.label;
});
const remapped_labels = {};
attr_labels.forEach((label) => {
remapped_labels[label.abbreviation] = label.label;
});
if there is a better way , thx to tell
S
ScriptyChris633d ago
This should work
const remapped_labels = Object.fromEntries(
attr_labels.map(({ abbreviation, label }) => [abbreviation, label])
)
const remapped_labels = Object.fromEntries(
attr_labels.map(({ abbreviation, label }) => [abbreviation, label])
)
M
_mercury633d ago
Very good .. works
S
ScriptyChris633d ago
Okay
UU
Unknown User633d ago