get first n elements of object javascript

Viewed 123

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', ...},
}
4 Answers

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)

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

const result = Object.values(obj).slice(0, 3);

You can use the reduce method. The sliced object is populated inside the reducer function (callback function) of the reduce() method.

let sliced = Object.keys(parentObject).slice(start,end).reduce((result, key) => {
result[key] = parentObject[key];
return result;}, {})
Related