如何从字符串数组生成含单个键值对的对象数组?
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

