мы проверяем, существует ли уже объект возраста, если да, мы добавляем новый объект, используя оператор распространения;если нет, мы вставляем объект;
релевантный код :
<code>import React, { useState } from "react";
import styled from "styled-components";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [num, setNum] = useState(0);
const [arr, setArr] = useState([
{
name: "child",
pax: {}
}
]);
function appendage({ id, age }) {
console.log("inside appendage with ", id, " and age:", age);
const toSaveArr = arr.map(o => {
if (o.name === "child") {
if (o.age) {
console.log("age exists");
o.age = [
...o.age,
{
id: id,
age: age
}
];
console.log("O", o);
} else {
o.age = [
{
id: id,
age: age
}
];
console.log("O", o);
}
/*return {
...o,
age: o.age
? o.age.map(o2 => {
if (o2.id === id) {
return {
id: o2.id,
age
};
}
console.log("o2", o2);
//something is wrong here
//why is it not adding new object?
return [
...o2,
{
id,
age
}
];
})
: [{ id, age }]
};
*/
}
return o;
});
setArr(toSaveArr);
}
return (
<div className="App">
<h1>{num}</h1>
<button
onClick={() => {
setNum(num + 1);
appendage({
id: num + 1,
age: num + 1
});
}}
>
add
</button>
<button>update age where id equal to 2</button>
<pre>{JSON.stringify(arr, null, 2)}
);} const rootElement = document.getElementById ("root");ReactDOM.render (, rootElement);
рабочий код и поле здесь