Suppose I have the object a
const a = {
string1: 'prop1',
val1: 'value1',
string2: 'prop2',
val2: 'value2'
}
then I can easily instantiate a new constant object b
const b = { [a['string1']]: a['val1'], [a['string2']]: a['val2'] };
which will result in
b = { prop1: 'value1', prop2: 'value2' }
But what if I have instead a list lst
const lst = [['prop1','value1'], ['prop2','value2']]
and I want to instantiate b from lst in a neat way? The furthest I got was
const b = {};
for(const tpl of lst){
b[tpl[0]] = tpl[1];
}
But me, being a big fan of oneliners, do not really like this code. So how can I quickly initialise b from a list of properties?
EDIT
It seems my question was not posed abstractly enoughed.
Let me reclarify it.
Suppose I have the list l = ['prop1', 'prop2'];
and the function fx(str) { return str.substring(1); }
How could I now quickly initialize the object b such that
b = {
prop1: 'rop1',
prop2: 'rop2'
}
I cannot do b= {[l[0]]=fx(l[0]), [l[1]]=fx(l[1])} since the list l is dynamicly generated and will contain an unknown amount of variables. So somehow it would be nice to loop
e.g. this non-existent syntax
b = { [[for str in l]] : fx(str) }
You have entries there, so you can just:
Object.fromEntries(lst)
You can use the .values() method
const b = {};
const lst = [
['prop1', 'value1'],
['prop2', 'value2'],
];
for (const [key, value] of lst.values()) b[key] = value;
console.log(b);