最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

get first n elements of object javascript - Stack Overflow

programmeradmin5浏览0评论

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

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', ...},
}
Share Improve this question edited Jul 1, 2022 at 5:43 Jon Sud asked Jul 1, 2022 at 5:41 Jon SudJon Sud 11.7k31 gold badges103 silver badges228 bronze badges 1
  • Keys are not always in the same order. Keys != indexes. – Nora Commented Jul 1, 2022 at 5:56
Add a ment  | 

3 Answers 3

Reset to default 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)

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

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;}, {})
发布评论

评论列表(0)

  1. 暂无评论