0

I have following array of tuple, need to make an object from, how?

Object.keys(invoiceItems)?.map(function (key, item) {
  [key, 1];
}

I know in Swift Dictionary(uniqueKeysWithValues: method call I need, what about in Typescript?

János
  • 32,867
  • 38
  • 193
  • 353

2 Answers2

3

Assuming that by tuples you mean two-element arrays, you can use Object.fromEntries to create such object:

const entries = [
  [ "value1", 42 ],
  [ "value2", 17 ],
  [ "value3", 51 ],
];

const object = Object.fromEntries(entries);

console.log(object);
Parzh from Ukraine
  • 7,999
  • 3
  • 34
  • 65
  • still a problem, would you check? https://stackoverflow.com/questions/69108183/typescipt-why-object-fromentries-does-not-accept-array-of-tuple – János Sep 08 '21 at 18:43
0

Here I assume your invoice items with some dummy data, below are 2 ways to create object with key:value

const invoiceItems = [[101, 'Coffee'], [102, 'Tea'], [103, 'Book']]

// Method 1
const o =  Object.fromEntries(invoiceItems);
console.log('o :', o)


// Method 2
const o2 = {}
Object.keys(invoiceItems).forEach(i => o2[invoiceItems[i][0]] = invoiceItems[i][1])
console.log('o2 :', o2)
Wasit Shafi
  • 854
  • 1
  • 9
  • 15