ganesh kaspate
ganesh kaspate

Reputation: 2695

Get the last Item which is an object from an array of objects

I am trying to get the last object from an array of the objects using following way,

const rowLen = previous_data.High.length;
          var temp = previous_data.High.map((object,i) => {
             if (rowLen === i + 1) {
                return object;
            }
        });

and then I want to fill the values in the next object so, I am doing like

temp[0].keyname .

Now while getting temp it is returning me the array of object so after 2nd I get

[ 0: undefined, 1: {key:value}]

So, I am not understanding why is it returning the array and also the previous one I want only last object .

Upvotes: 0

Views: 3707

Answers (3)

zer00ne
zer00ne

Reputation: 44108

Destructuring assignment allows you to assign variables, swap properties, ignore properties, assign default values, access as many properties as you want.


Demo

let arrObj = [{
    key0: "value0",
    key1: "value1",
    key2: "value2",
    key3: "value3"
  },
    [1, 2, 3],
  {
    key4: "value4"
  }];

let [{key0:K0,key1:K1,key2:K2,key3:K3},[a, b, c],{key4:last}] = arrObj;

  console.log(last);
  console.log(c);
  console.log(K1);

Upvotes: 0

Tarek Essam
Tarek Essam

Reputation: 4010

Because map return an array you use map when you want to alter the original array not to select an element. Do it like this. previous_data.High[previous_data.High.length -1]. This will get you the last element.

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 282140

Map returns a value for each iteration of the array. If you return a value from the callback function within map, that value is returned at the respective index else undefined is returned which is what you can see

Since you want only the last value from array, you could simply use slice

var temp = previous_data.High.slice(-1);

Upvotes: 3

Related Questions