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

  • I can only guess what you actually want to achieve, so ill provide some different solutions.

    The thing i think you want to do is, only get the values "ownerSurname", "color" and "bark" for each of your objects in your array. That could be achieved like this:

    [{name: "name", age: 20}].map(value => ({name: value.name}))
    

    As explanation: This code maps through every object, and then returns a new object with only the "name" field in it. You could change this code to your specific example.

    I can also imagine, that you might want to omit all other values from only one object. This might be a misunderstanding when coming from other languages like phps where objects are handled with brackets. You could just do that by removing the brackets from your "myValues" like this:

    const myObject = {name: "name", age: 19}
    const myNewObject = {name: myObject.name}
    

    Please note that slice takes the last 3 values of an array, not an object. Please see the difference here: https://medium.com/@zac_heisey/objects-vs-arrays-42601ff79421