Home > Blockchain >  map or foreach on an array of objects but only for the fist 5 objects
map or foreach on an array of objects but only for the fist 5 objects

Time:11-24

I have an array of objects but I only want to loop through the first 5 objects and break, whats the best way to do that.

[
  {"visibility": 10000,},
  {"visibility": 10000,},
  {"visibility": 30000,},
  {"visibility": 40000,},
  {"visibility": 10000,}, -----> exit here
  {"visibility": 20000,},
  {"visibility": 90000,},
  {"visibility": 230000,},
  {"visibility": 10000,},
  {"visibility": 70000,},
]

CodePudding user response:

Just using Array.slice() can do it

console.log(data.slice(0,5))

let data = [
  {"visibility": 10000,},
  {"visibility": 10000,},
  {"visibility": 30000,},
  {"visibility": 40000,},
  {"visibility": 10000,},
  {"visibility": 20000,},
  {"visibility": 90000,},
  {"visibility": 230000,},
  {"visibility": 10000,},
  {"visibility": 70000,},
]

console.log(data.slice(0,5))

CodePudding user response:

write a below code

import React from "react";

const employees = [
 { id: 1, name: "Alice", country: "Austria" },
 { id: 2, name: "Bob", country: "Belgium" },
 { id: 3, name: "Carl", country: "Canada" },
 { id: 4, name: "Delilah", country: "Denmark" },
 { id: 5, name: "Ethan", country: "Egypt" },
 { id: 6, name: "Alice", country: "Austria" },
 { id: 7, name: "Bob", country: "Belgium" },
 { id: 8, name: "Carl", country: "Canada" }
];

function App() {
return (
<>
  <div>
    {employees.slice(0, 4).map((employee, index) => {
      return (
        <div key={index}>
          <h2>name: {employee.name}</h2>
          <h2>country: {employee.country}</h2>

          <hr />
        </div>
      );
    })}
  </div>
 </>
 );
}

export default App;

OUTPUT

name: Alice
country: Austria
---------------------
name: Bob
country: Belgium
---------------------
name: Carl
country: Canada
---------------------
name: Delilah
country: Denmark
---------------------

link :- https://codesandbox.io/embed/modest-breeze-71n13n?fontsize=14&hidenavigation=1&theme=dark

CodePudding user response:

Here you can try this logic :

let arr = [
  {"visibility": 10000,},
  {"visibility": 10000,},
  {"visibility": 30000,},
  {"visibility": 40000,},
  {"visibility": 10000,},
  {"visibility": 20000,},
  {"visibility": 90000,},
  {"visibility": 230000,},
  {"visibility": 10000,},
  {"visibility": 70000,},
];

let newArr = [];

arr.map((obj,index) => {
if(index < 5){
newArr.push(arr[index]);
};

});

console.log(newArr);

  • Related