Search code examples
javascriptarraysobject

How can I get last three values from array of objects


I have an array of object with a few values. I would like to get only last, three values (ownerSurname, color and bark).

I tried to use slice or length but with failure.

const myValues: MyValues<string>[] = [
   {
    name: "Lucky",
    surname: "Luck",
    age: "3",
    breed: "Shepherd",
    owner: "Paul",
    ownerSurname: "Luck",
    color: "Brown",
    bark: "All the time",
  },
]
const newData = myValues.slice(-3)
<MyComponent value={newData}/>

Solution

  • This is more related to simple Javascript rather than React.

    If you really would like to know, first you need to "get" the object itself, in this case because is an array with one single element it is only a matter of select the [0] index.

    const myValues: MyValues<string>[] = [
       {
        name: "Lucky",
        surname: "Luck",
        age: "3",
        breed: "Shepherd",
        owner: "Paul",
        ownerSurname: "Luck",
        color: "Brown",
        bark: "All the time",
      },
    ]
    
    const obj = myValues[0];
    
    const newObj = { 
      ownerSurname: obj.ownerSurname, 
      bark: obj.bark, 
      color: obj.color 
    };
    
    <MyComponent value={newObj}/>
    

    These are basic functions of javascript and are not related to React. Perhaps you need to find more basic lessons on how objects and arrays work in Javascript.