If you target modern browsers or use some kind of transpiler you may use Object.entries to map [key, value]
pairs within single iteration.
const obj = {
foo: 'bar',
baz: 42
}
console.log('Object.entries')
console.log(
Object.entries(obj)
)
console.log('Mapping')
console.log(
Object.entries(obj)
.map( ([key, value]) => `My key is ${key} and my value is ${value}` )
)
Usage with React
Object.entries
function is very handy with React as by default there is no easy iteration of objects/dictionaries. React requires you to assign keys to components when iterating in order to perform it's diffing algorithm. By using Object.entries
you can leverage already keyed collections without manually injecting keys in your data or using array indices, which can lead to undesired behavior when indices change after filtering, removing or adding items.
Please see following example of Object.entries
usage with React:
const buttonCaptions = {
close: "Close",
submit: "Submit result",
print: "print",
}
const Example = () =>
<div>
{
Object.entries(buttonCaptions)
.map( ([key, value]) => <button key={key}>{value}</button> )
}
</div>
ReactDOM.render(<Example />, document.getElementById('react'));
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Common syntax errors
As a side note, please keep in mind that when mapping result of the Object.entries
you must wrap the array argument in parentheses when using array destructuring. Following code will throw syntax error:
console.log(
Object.entries({key: 'value'})
.map([key, value] => `${key}: ${value}`)
)
Do this instead:
console.log(
Object.entries({key: 'value'})
.map( ([key, value]) => `${key}: ${value}` )
)
console.log(
Object.entries({key: 'value'})
.map(keyValuePair => `${keyValuePair[0]}: ${keyValuePair[1]}`)
)
Compatibility
For the current browser support please see the ECMAScript compatibility table under 2017 features > Object static methods.