I have two arrays of objects that I want to merge into a single array and merge their objects too.
The two arrays:
const itemsFr = [
{
title: "Bonjour"
},
{
title: "Bonne Nuit"
}
];
const itemsEn = [
{
title: "Good Morning"
},
{
title: "Good Night"
}
];
The result that I want:
items = [
{
title: {
fr: "Bonjour",
en: "Good Morning"
}
},
{
title: {
fr: "Bonne Nuit",
en: "Good Night"
}
}
];
Here is what I tried:
export default function App() {
const [items, setItems] = useState([]);
const itemsFr = [
{
title: "Bonjour"
},
{
title: "Bonne Nuit"
}
];
const itemsEn = [
{
title: "Good Morning"
},
{
title: "Good Night"
}
];
const fillItemsFrArray = () =>
itemsFr.map((item) => {
setItems(...items, {
title: {
fr: item.title
}
});
});
const fillItemsEnArray = () =>
itemsEn.map((item) => {
setItems(...items, {
title: {
en: item.title
}
});
});
useEffect(() => {
fillItemsFrArray();
fillItemsEnArray();
}, []);
return (
<div className="App">
<h2>{JSON.stringify(items, null, 4)}</h2>
</div>
);
}
Here is the CodeSandbox link: https://codesandbox.io/s/restless-night-xq6qg?file=/src/App.js:670-1166