Home > OS >  deconstructing an object in react gives another object with a key of 0
deconstructing an object in react gives another object with a key of 0

Time:12-16

I have an array of objects and I'm trying to pass all the values of one element from that array as prop to a child component:

const ParentComponent = () => {
  const [selectedBillNumber,setSelectedBillNumber] = useState(2);

  const data = [
   {bill_number: 1, key2: value2, key3: value3, etc...},
   {bill_number: 2, key2: value2, key3: value3, etc...},
   {bill_number: 3, key2: value2, key3: value3, etc...},
  ];

 return <ChildComponent {...data.filter(elem => elem.bill_number === selectedBillNumber)} />;
}

I expect that the filter function when applied to the data array to return an object whose bill_number is equal to 2, and that the spread operator deconstructs the object so I could pass the keys of the object as props to my child component like this:

const ChildComponet = ({ bill_number, key2, key3, etc... }) => {
 // use the keys here
}

However when I console log it: console.log({...data.filter(elem => elem.bill_number === selectedBillNumber)}), what I get is another object who has a key of 0 and mapped to the value I expected in the first place: enter image description here

To solve this issue I return the following in my parent component:

return <ChildComponent {...data.filter(elem => elem.bill_number === selectedBillNumber)["0"]} />;

I would to understand why am I getting a new object with a key of 0 mapped to to the values I need instead of directly receiving the value and what should I change in my code to directly get those values without having to use ["0"] at the end of the filter fucntion.

CodePudding user response:

It's because you use filter: this function returns an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter.

If you want only one item you can use find instead: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

<ChildComponent {...data.find(elem => elem.bill_number === selectedBillNumber)} />;

CodePudding user response:

As Konrad commented, the filter function will return an array, even though it only contains one element, you still need to reference it as an array. So you need to select the first element ( ["0"] ). If that makes you feel uncomfortable, you can use the .pop() method of the array:

const ParentComponent = () => {
  const [selectedBillNumber,setSelectedBillNumber] = useState(2);

  const data = [
   {bill_number: 1, key2: value2, key3: value3, etc...},
   {bill_number: 2, key2: value2, key3: value3, etc...},
   {bill_number: 3, key2: value2, key3: value3, etc...},
  ];

 return <ChildComponent {...data.filter(elem => elem.bill_number === selectedBillNumber).pop()} />;
}

  • Related