Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
get first n elements of object javascript

I have object (not array) with key and value:

const obj = {
 1: { id: 1, name: 'name', ...},
 2: { id: 2, name: 'name', ...},
 3: { id: 3, name: 'name', ...},
 4: { id: 4, name: 'name', ...},
 5: { id: 5, name: 'name', ...},
 6: { id: 6, name: 'name', ...},
}

How I get the first 3 elements of this object in javascript?

For example I want to get 3 the object I expect is (with key and value):

const obj = {
 1: { id: 1, name: 'name', ...},
 2: { id: 2, name: 'name', ...},
 3: { id: 3, name: 'name', ...},
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use Object.entries and slice it and then convert it back to an object using Object.fromEntries

const obj = {
 1: { id: 1, name: 'name'},
 2: { id: 2, name: 'name'},
 3: { id: 3, name: 'name'},
 4: { id: 4, name: 'name'},
 5: { id: 5, name: 'name'},
 6: { id: 6, name: 'name'},
}
let sliced = Object.fromEntries(Object.entries(obj).slice(0,3))

console.log(sliced)

about 4 years ago · Juan Pablo Isaza Report

0

You could use JavaScript for...in loop as the code below:

const obj = {
 1: { id: 1, name: 'name'},
 2: { id: 2, name: 'name'},
 3: { id: 3, name: 'name'},
 4: { id: 4, name: 'name'},
 5: { id: 5, name: 'name'},
 6: { id: 6, name: 'name'},
};

const newObj = {};

let maxCount = 3; /* define the number of elements you want to get from original object here */
let count = 0;

for (let item in obj) {
    newObj[item] = obj[item];
    count++;
    if(count>=maxCount) {
        break;
    }
}

console.log(newObj);

about 4 years ago · Juan Pablo Isaza Report

0

const result = Object.values(obj).slice(0, 3);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!