如何从JavaScript中的JSON对象获取没有键的值

时间:2018-11-23 08:27:02

标签: javascript json

我有一个如下所示的JSON对象,我想在数组中检索值而无需传递密钥

 var myData={
  "VALUEX": "GrandTotal",
  "VALUEX2": "GrandTotal",
  "Jan-2018": 25,
  "Feb-2018": 54.5,
  "Mar-2018": 84,
  "Apr-2018": 45.2,
  "May-2018": 46,
  "Jun-2018": 76.5,
  "Jul-2018": 107,
  "Aug-2018": 138,
  "Sep-2018": 168.5,
  "Oct-2018": 199,
  "Nov-2018": 229.5,
  "Dec-2018": 260
}

2 个答案:

答案 0 :(得分:5)

有几种方法可以获取对象的值而无需使用key

使用 Object.values()

var myData = {"VALUEX":"GrandTotal","VALUEX2":"GrandTotal","Jan-2018":25,"Feb-2018":54.5,"Mar-2018":84,"Apr-2018":45.2,"May-2018":46,"Jun-2018":76.5,"Jul-2018":107,"Aug-2018":138,"Sep-2018":168.5,"Oct-2018":199,"Nov-2018":229.5,"Dec-2018":260}
console.log(Object.values(myData));

使用 Object.entries()

var myData = {"VALUEX":"GrandTotal","VALUEX2":"GrandTotal","Jan-2018":25,"Feb-2018":54.5,"Mar-2018":84,"Apr-2018":45.2,"May-2018":46,"Jun-2018":76.5,"Jul-2018":107,"Aug-2018":138,"Sep-2018":168.5,"Oct-2018":199,"Nov-2018":229.5,"Dec-2018":260}
var arrayVal = Object.entries(myData).map(item => item[1]);
console.log(arrayVal);

使用 Object.keys()

var myData = {"VALUEX":"GrandTotal","VALUEX2":"GrandTotal","Jan-2018":25,"Feb-2018":54.5,"Mar-2018":84,"Apr-2018":45.2,"May-2018":46,"Jun-2018":76.5,"Jul-2018":107,"Aug-2018":138,"Sep-2018":168.5,"Oct-2018":199,"Nov-2018":229.5,"Dec-2018":260}
var arrayVal = [];
Object.keys(myData).forEach(key => arrayVal.push(myData[key]));
console.log(arrayVal);

答案 1 :(得分:0)

您可以使用以下表示法:

myData [“ VALUEX”]

这将翻译为“ GrantTotal”。

要在键及其值之间进行迭代,可以执行以下操作:

for(var key in myData){
    if(myData.hasOwnProperty(key){
        console.log(myData[key]);
    } 
}