Today I Learned - Rocky Kev

TIL fancy methods to transform Javascript Objects

POSTED ON:

TAGS:

We got a bunch of fancy methods to transform objects.

Objects and Arrays

Object.entries(originalObject)
This object method takes an object and returns a new 2-dimensional array with each nested array containing the original object’s key and value as string.

const fruitObject = {
'banana': 'yellow',
'strawberry': 'red',
'tangerine': 'orange'
};

console.log(Object.entries(fruitObject));
// [["banana", "yellow"], ["strawberry", "red"], ["tangerine", "orange"]]

Object.fromEntries(anIterable)

const fruitArray = [
['banana': 'yellow'],
['strawberry': 'red'],
['tangerine': 'orange'],
];

console.log(Object.fromEntries(fruitArray));
// { banana: 'yellow', strawberry: 'red', tangerine: 'orange' }

Object Keys

Object.keys(anObject) & Object.values(anObject)
This object method accepts an object as an argument and returns an array containing the object’s keys as elements.

const fruitObject = {
'banana': 'yellow',
'strawberry': 'red',
'tangerine': 'orange'
};

console.log(Object.entries(fruitObject));
// ["banana", "strawberry", "tangerine"]

console.log(Object.values(fruitObject));
// ["yellow", "red", "orange"]

via The Coolest JavaScript Features from the Last 5 Years


Related TILs

Tagged:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL a neat way to clone and object and override the items

Spread the object into a new object, then override the element later.

TIL You can dynamically name objects

Not all Object keys have to be hard-coded strings. To make it dynamic, use [brackets].