简单的对象值检索

时间:2016-08-04 06:01:04

标签: javascript json node.js

我有一个对象从一个包含此{ "query1": 0.443}

的API返回给我

我试图通过使用:

来获得0.443
request(options, function (error, response, body)
            {
            if (error) throw new Error(error);
            var moo = 'query1';
            var cow = body[moo];
            console.log(cow);

但是价值显示为未定义。我忘记了什么?

3 个答案:

答案 0 :(得分:0)

List<dynamic> Joints = new List<dynamic>
{
    new { Id = 1, LineId = 1, JointName = "joint1" },
    new { Id = 2, LineId = 2, JointName = "joint2" },
    new { Id = 3, LineId = 1, JointName = "joint3" },
};

List<dynamic> Lines = new List<dynamic>
{
    new { Id = 1, LineName = "line1" },
    new { Id = 2, LineName = "line2" },
    new { Id = 3, LineName = "line3" },
};

List<dynamic> FitUpDetails = new List<dynamic>
{
    new { Id = 1, JointId = 1, FitUpdate = new DateTime(2012,12,12), State = "acc" },
    new { Id = 2, JointId = 1, FitUpdate = new DateTime(2013,12,12), State = "rej" },
    new { Id = 1, JointId = 2, FitUpdate = new DateTime(2015,12,12), State = "acc" },
    new { Id = 4, JointId = 2, FitUpdate = new DateTime(2016,12,12), State = "rej" },
};

或者你只需​​使用点符号来访问属性

var body = { "query1": 0.443 };
var moo = 'query1';
var cow = body[ moo ];
console.log(cow);

答案 1 :(得分:0)

这很简单:

var data = { "query1": 0.443 }

console.log(data.query1)

因此,如果您的对象以ajax响应名称data返回,只需

var myVal = data.query1

答案 2 :(得分:0)

以上所有答案都是使用键获取对象值的好方法!我忘了在API返回给我的对象上使用JSON.parse了!

request(options, function (error, response, body)
        {
        if (error) throw new Error(error);
        var holder = JSON.parse(body);
        console.log(holder.query1);

感谢所有回答的人!干杯!