如何将对象的不同键的值推送到数组中

时间:2018-03-13 12:38:27

标签: javascript arrays object

我有一个对象数组,我希望得到一个具有内部对象值的新数组。

"vals": [{
            "vals_OwnGeneratingStation": [
                ["Hydel Power Station", "0.000"],
                ["Thermal Power Station", "0.000"],
                ["Small Hydel Units", "0.000"],
                ["Mini-Hydro", "0.000"]
            ]
        },
        {
            "vals_EnergyPurchaseWithinState": [
                [null, "0.000"]
            ]
        },
        {
            "vals_EnergyPurchaseOutsideState": [
                [null, "0.000"]
            ]
        },
        {
            "vals_Others": [
                [null, "0.000"]
            ]
        }
    ]

我想要一个值为“vals_OwnGeneratingStation”,“vals_OwnGeneratingStation”,“vals_EnergyPurchaseOutsideState”,“vals_Others”的数组

数组看起来像

newArray = [
[
  ["Hydel Power Station", "0.000"],
  ["Thermal Power Station", "0.000"],
  ["Small Hydel Units", "0.000"],
  ["Mini-Hydro", "0.000"]
],
[
 [null, "0.000"]
],
[
 [null, "0.000"]
],
[
 [null, "0.000"]
]

2 个答案:

答案 0 :(得分:0)

使用mapObject.values

newArray =  vals.map( s => Object.values( s )[0] )

<强>演示

&#13;
&#13;
var vals = [{
    "vals_OwnGeneratingStation": [
      ["Hydel Power Station", "0.000"],
      ["Thermal Power Station", "0.000"],
      ["Small Hydel Units", "0.000"],
      ["Mini-Hydro", "0.000"]
    ]
  },
  {
    "vals_EnergyPurchaseWithinState": [
      [null, "0.000"]
    ]
  },
  {
    "vals_EnergyPurchaseOutsideState": [
      [null, "0.000"]
    ]
  },
  {
    "vals_Others": [
      [null, "0.000"]
    ]
  }
];
var newArray = vals.map(s => Object.values(s)[0]);
console.log(newArray);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个

vals.map(item => Object.values(item));