You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串数组生成含单个键值对的对象数组?

Convert Count Object to Array of Single-Key Objects

Hey there! Nice work using reduce to get your count object—let's turn that into the array format you're looking for. There are a couple of clean, modern ways to do this in JavaScript:

Method 1: Use Object.entries() + map()

This is probably the most straightforward approach, since Object.entries() directly gives you key-value pairs to work with:

const countObj = {1005: 3, 1006: 3, 1007: 2};
const resultArray = Object.entries(countObj).map(([key, value]) => ({ [key]: value }));

console.log(resultArray);
// Output: [{"1005":3},{"1006":3},{"1007":2}]

Here's what's happening step-by-step:

  • Object.entries(countObj) converts your object into an array of [key, value] pairs: [["1005", 3], ["1006", 3], ["1007", 2]]
  • The map() function iterates over each pair, using computed property names ([key]) to create a new object with just that single key-value pair.

Method 2: Use Object.keys() + map()

If you prefer to work with just the keys first, this method works too:

const countObj = {1005: 3, 1006: 3, 1007: 2};
const resultArray = Object.keys(countObj).map(key => ({ [key]: countObj[key] }));

This time, Object.keys(countObj) gives you an array of the object's keys (["1005", "1006", "1007"]), and we map each key to a new object where we look up the value from the original count object.

Both methods are concise and leverage ES6 features to get the job done cleanly.

内容的提问来源于stack exchange,提问作者WannaBeBetter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:09:29