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

如何在JavaScript中通过循环将对象的键值对拆分到不同的数组对象中?

Fixing Your For Loop to Get the Desired Array Output

Hey there! Let's sort out that loop issue for you. The problem with your original code is that you're trying to loop over the object directly in a for loop designed for numeric values—which doesn't work. You end up pushing the entire object into the array instead of each individual age value.

Here's What Went Wrong

Your original loop:

for (i= obj;i<=obj;i++) { 
  years.push({ edad_beneficiario : i }) 
}

This logic doesn't apply to objects: you can't compare an object to itself with <=, and incrementing an object (i++) does nothing meaningful. That's why you got an array containing the whole object instead of separate age entries.

Correct Solutions

We need to iterate over the values of your obj object instead. Here are a few straightforward, scalable ways to do this:

Method 1: Use for...of with Object.values()

This is the cleanest modern approach—Object.values() returns an array of all the values in your object, then we loop through each value:

let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'} 
var years = []; 

for (const age of Object.values(obj)) {
  years.push({ edad_beneficiario: age });
}

console.log(years); // Output: [{edad_beneficiario:"32"}, {edad_beneficiario:"5"}]

Method 2: Iterate Over Object Keys (for older browser compatibility)

If you need to support older environments where Object.values() isn't available, loop over the object's keys and fetch each value manually:

let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'} 
var years = []; 

for (const key of Object.keys(obj)) {
  const age = obj[key];
  years.push({ edad_beneficiario: age });
}

Method 3: Use forEach for a Concise Style

You can also use forEach to loop through the values in one concise block:

let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'} 
var years = []; 

Object.values(obj).forEach(age => {
  years.push({ edad_beneficiario: age });
});

All of these methods will give you the exact output you're looking for, and they're scalable too—if you add more EdadBeneficiario properties later, the loop will handle them automatically without extra manual code!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:12:47