Home > Enterprise >  Javascript: quick object initialization by list
Javascript: quick object initialization by list

Time:06-02

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?

CodePudding user response:

You have entries there, so you can just:

Object.fromEntries(lst)

CodePudding user response:

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);

CodePudding user response:

As Uroš mentioned Object.fromEntries(lst) is the best method for this. As an alternative you can use reduce.

const lst = [['prop1','value1'], ['prop2','value2']]

const b =  lst.reduce(function(prev,curr){prev[curr[0]]=curr[1];return prev;},{})
console.log(b);

  • Related