screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState } = React; const App = () => { // Sample arrays with data const [array1, setArray1] = useState([ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, ]); const [array2, setArray2] = useState([ { id: 1, description: 'Description 1' }, { id: 3, description: 'Description 3' }, ]); // Function to add items from array2 to array1 based on matching IDs const mergeArrays = () => { const mergedArray = array1.map((item1) => { const matchingItem = array2.find((item2) => item2.id === item1.id); // If a matching item is found in array2, merge them if (matchingItem) { return { ...item1, ...matchingItem, }; } // If no matching item is found, return the original item from array1 return item1; }); // Update state with the merged array setArray1(mergedArray); }; return ( <div className='container'> <h3>React Js Add item from array to another array where is same id</h3> <button onClick={mergeArrays}>Merge Arrays</button> <p> {JSON.stringify(array1)}</p> </div> ); } ReactDOM.render(<App />, document.getElementById('app')); </script> <style> .container { border-radius: 8px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); padding: 20px; margin: 20px auto; max-width: 400px; text-align: center; } </style> </body> </html>