从数组内部的JSON对象内部获取记录

时间:2018-07-18 11:12:34

标签: javascript json chakram

我有一个采用这种格式的API响应。

 [{
 "response_data": {
    "0":{
    "id" : 0,
    "office" : "India",
    "type" : 'Perm'
    },
    "1":{
    id : 0,
    "office" : "America",
    "type" : 'Perm'
    },
    "2":{
    id : 0,
    "office" : "Europe",
    "type" : 'Contract'
    },
    "2":{
    id : 0,
    "office" : "Latin America",
    "type" : 'Contract'
    }

    }}]

我正在尝试获取officetype的所有Contract。我将json响应保存在一个变量中-使用Chakram作为

var response_json = t.body[0].response_data;

这使我在console.log中的正确回答为

       "0":{
    "id" : 0,
    "office" : "India",
    "type" : 'Perm'
    },
    "1":{
    id : 0,
    "office" : "America",
    "type" : 'Perm'
    },
    "2":{
    id : 0,
    "office" : "Europe",
    "type" : 'Contract'
    },
    "2":{
    id : 0,
    "office" : "Latin America",
    "type" : 'Contract'
    }

现在如何获取json中相应的键并提取所需的信息。我尝试了此操作,但返回了undefined

var length = Object.keys(response_json).length;
for(var i = 0; i<= length;i++){
console.log(response_json.i) //returns undefined
 console.log((Object.keys(response_json)).id); //returns undefined.
}

我知道,如果响应是数组,则可以使用filter方法解决此问题,但是如何在JSON对象中执行相同的操作?我正在寻找一种优化的解决方案,因为API返回了将近5000个对象。 如果已经问过这个问题,请提供参考,因为我在SO上找不到任何内容。

4 个答案:

答案 0 :(得分:1)

如果要使用过滤器方法执行此操作 一种解决方法是添加一个属性长度,然后使用Array.from,如下所示。然后,您可以使用Array.prototype.filter方法。

let o = {
    '0': {
        id: 0,
        "office": "India",
        "type": 'Perm'
    },
    '1': {
        id: 0,
        "office": "America",
        "type": 'Perm'
    },
    '2': {
        id: 0,
        "office": "Europe",
        "type": 'Contract'
    }
};

o.length = Object.keys(o).length;
let a = Array.from(o);

let r = a.filter(({ type }) => type == 'Contract');
console.log(r);

答案 1 :(得分:0)

您的代码有两个主要错误,一个是使用loop直到array的长度,其中索引从0开始。第二个错误是使用括号而不是{{1 }}。因此,如下更新代码:

dot

答案 2 :(得分:0)

在您的response_json'0','1'上,所有键均为字符串格式。 但是在您的for循环中,“ i”是整数,因此密钥不可用。只要将其转换为字符串,就可以得到想要的结果 像console.log(response_json [''+ i])

答案 3 :(得分:0)

branch_2

如果记录超过5千条,在javascript中可能不会更好,请在服务器端更好地处理它。