Steve
Steve

Reputation: 297

Javascript: How to iterate only a certain part of a javascript object?

I have a javascript object that looks like this

const columns = {
    firstLabel: 'Hello',
    secondLabel: 'world',
    thirdLabel: 'I',
    fourthLabel: 'Am',
    fifthLabel: 'Paul',
};

I am trying to only get the values of the last three I, Am, Paul. I am doing something like this but this clearly doesn't work as this will return everything. Is this possible to do with an object?

 for(const prop in columns) {
      if(Object.keys(columns).length > 2){
        console.log(`${columns[prop]}`);
      }
 }

Expected output is just:

I

Am

Here

Upvotes: 0

Views: 40

Answers (1)

jorgeadev
jorgeadev

Reputation: 119

Try with,

const lastThree = Object.values(columns).slice(-3);
console.log(lastThree);

The answer is:

[ 'I', 'Am', 'Paul' ]

Upvotes: 1

Related Questions