skip to Main Content

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}/>

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search