本文介绍了将对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 Object.keys()转换对象

var obj1={
    "jan": {
        "COAL": "25"
    },
    "feb": {
        "ROM": "50",
        "WASTE": "55"
    },
    "april": {
        "COAL": "60"
    }
}

var obj2=[
    {
        "month": "jan",
        "product": "COAL",
        "quantity": "25"
    },
    {
        "month": "feb",
        "product": "ROM",
        "quantity": "50"
    },
    {
        "month": "feb",
        "product": "WASTE",
        "quantity": "55"
    },
    {
        "month": "april",
        "product": "COAL",
        "quantity": "60"
    }
]

但在中间失败了,因为我无法计算属性,例如在 feb中两种产品s ROM和 WASTE,但是最多可以达到3或4。有人可以建议解决此问题的方法吗?

but failed in the middle as I'm not able to calculate the properties say for example in "feb" there are two products "ROM" and "WASTE", but this can go upto 3 or 4. Can anyone please suggest possible solution for this problem?

推荐答案

这将做到:

var res = []
for(i in obj1){
 var rowObj = obj1[i];
 for(j in rowObj){
     var newObj = {'month' : i, 'product' : j, 'quantity' : rowObj[j]}
     res.push(newObj);
 }
}
console.log(res);

这篇关于将对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:20