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>
  )

1 Answers1

-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

malarres
  • 2,941
  • 1
  • 21
  • 35
  • 1
    This is horrendous. There is no reason to use `filter` while `slice` is available. – Murat Karagöz Jan 22 '21 at 10:57
  • 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: https://medium.com/@justintulk/javascript-performance-array-slice-vs-array-filter-4573d726aacb – malarres Jan 22 '21 at 11:05
  • 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. – Jonas Wilms Jan 22 '21 at 11:32