I'd like to know how i can update object in array.
I asked this question before, and I got the hint at the moment but i can't still figure it out how to update x and y , so here is my piece code :
const [data, setdata] = useState([
{ x: 1, y: 2 },
{ x: 1, y: 2 },
{ x: 1, y: 2 },
]);
const x= [3, 4, 5, 6, 7, 8, 9];
const y =[ 1,2,3,4,6,7];
const updateX = () => {
setdata((data) => data.map((d, i) => ({ ...d, x: newData[i] })));
setdata((data) => data.map((d, i) => ({ ...d, y: newData[i] })))
};
/////result ///
{ x: 3, y: 2 },
{ x: 4, y: 2 },
{ x: 5, y: 2 },
/// what i want ///
{ x: 3, y: 1 },
{ x: 4, y: 2 },
{ x: 5, y: 3 },
{ x: 6, y: 4 },
{ x: 7, y: 5 },
{ x: 8, y: 6 },
{ x: 9, y: 7 },
I don't quite understand why you are initializing the data object with those values.
The result you want, you can't get it by iterating the data object that you have initialized with 3 values.
Assuming that the arrays have these values and an equal length, you can try this:
const [data, setdata] = useState([
{ x: 1, y: 2 },
{ x: 1, y: 2 },
{ x: 1, y: 2 }
]);
const x = [3, 4, 5, 6, 7, 8, 9];
const y = [1, 2, 3, 4, 5, 6, 7];
const newData = x.reduce((acc, xVal, index) => {
const obj = { x: xVal, y: y[index] };
acc.push(obj);
return acc;
}, []);
setdata(newData)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments