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?

6
  • 3
    Object.fromEntries Commented Sep 8, 2021 at 17:38
  • Does JavaScript actually have tuples (outside of this TC39 proposal)? Commented Sep 8, 2021 at 17:43
  • 1
    @jarmod Not exactly, but TypeScript does have a type signature for tuples that differs from arrays (though in execution, they behave the same). Commented Sep 8, 2021 at 17:44
  • @jarmod you have used 'let aa = Object.keys(invoiceItems).forEach((key)....' which will return undefined, try using the same with map!! Commented Sep 8, 2021 at 18:48
  • @WasitShafi no idea what you're referring to here. Nobody used forEach in this post. Commented Sep 8, 2021 at 18:53

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

still a problem, would you check? stackoverflow.com/questions/69108183/…
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.