3

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', ...},
}
1
  • Keys are not always in the same order. Keys != indexes. Commented Jul 1, 2022 at 5:56

3 Answers 3

6

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)

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

Comments

2

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

Comments

0

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;}, {})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.