0

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

2
  • 2
    Object.values(columns).slice(-3) Commented Apr 12, 2022 at 20:09
  • 2
    The order of keys in an object is not guaranteed and you shouldn't code for it Commented Apr 12, 2022 at 20:29

1 Answer 1

1

Try with,

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

The answer is:

[ 'I', 'Am', 'Paul' ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.