If you are targeting modern browsers or using some kind of transpiler, you can use Object.entries to match [key, value] pairs within a 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}` ) )
Use with React
Object.entries function is very convenient with React, because by default there is no simple iteration of objects / dictionaries. React requires that you assign keys to components during iteration in order to execute this algorithm. Using Object.entries , you can use already collected collections without manually entering keys into your data or using array indices, which can lead to undesirable behavior when the indices change after filtering, deleting, or adding items.
The following is an example of using Object.entries using 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, when displaying the result of Object.entries you must wrap the array argument in parentheses when using array destructuring. The following code will throw a 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 current browser support, see the ECMAScript Compatibility Table in Functions 2017> Static Object Methods.
source share