0

I've got the a list of objects iterating in object.keys, however how can I iterate between two numbers only(3-5)? And ignoring the rest of the list.

const obj = { '#1 List title': [{ title: 'First', }, ], '#2 List title': [{ title: 'Sec', }, ], '#3 List title': [{ title: 'Third', }, ], '#4 List title': [{ title: 'Fourth', }, ], '#5 List title': [{ title: 'Fifth', }, ], }; const listItem = Object.keys(obj).map((key) => <div key={key}> <div>{key}</div> <div> {obj[key].map(el => {el.title} )} </div> </div> ) 
2

1 Answer 1

-2

Filter can get you there also:

const obj = { '#1 List title': [{ title: 'First', }, ], '#2 List title': [{ title: 'Sec', }, ], '#3 List title': [{ title: 'Third', }, ], '#4 List title': [{ title: 'Fourth', }, ], '#5 List title': [{ title: 'Fifth', }, ], }; const start = 2; const end = 4; const listItem = Object.keys(obj).filter((_,i) => i >=start && i <=end).map((key) => ` <div key=${key}> <div>${key}</div> <div> ${obj[key].map(el => {el.title} )} </div> </div> ` ) console.log(listItem)

please notice that an array index starts at 0, modify start and end at your will

Sign up to request clarification or add additional context in comments.

3 Comments

This is horrendous. There is no reason to use filter while slice is available.
wow kind of a harsh adjective. i'm not saying that this solution is better, but at least it looks like there's room for discussion: medium.com/@justintulk/…
Well if this was your reason to choose to "reinvent the wheel", then I would reflect that in your answer. Currently it is overcomplicating things without giving any reason.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.