如何在typescript中访问json字符串中的嵌套数据

时间:2017-11-09 10:45:17

标签: json typescript

我有这个json结构,无法找到访问数据值(data1,data2和date)的方法,我希望在数组中包含这些值,而不是按日期排序:

{
"07" : {
  "07" : {
    "data1" : "-1",
    "data2" : "test",
    "date" : "1995-07-07"
  },
  "08" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-07-08"
  },
  "09" : {
    "data1" : "-1",
    "data2" : "test",
    "date" : "1995-07-09"
  },
  "10" : {
    "data1" : "-1",
    "data2" : "test",
    "date" : "1995-07-10"
  }
},
"08" : {
  "07" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-08-07"
  },
  "08" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-08-08"
  },
  "09" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-08-09"
  }
}
}

因为我的钥匙没有被定义为常数,所以我不知道他们提前做了什么。

2 个答案:

答案 0 :(得分:1)

Object.entries的Polyfill:

const reduce = Function.bind.call(Function.call, Array.prototype.reduce);
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable);
const concat = Function.bind.call(Function.call, Array.prototype.concat);
const keys = Reflect.ownKeys;

if (!Object.values) {
    Object.values = function values(O) {
        return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []);
    };
}

if (!Object.entries) {
    Object.entries = function entries(O) {
        return reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), []);
    };
}

代码:

for (const [key, value] of Object.entries(myObject))
        {
            for (const [key2, value2] of Object.entries(value))
            {
                value2.data1;
                value2.data2;
                value2.date;
            }
        }

相反,Object.entries可以枚举像this这样的对象。

for (var key in myObject)
{
    for (var key2 in myObject[key])
    {
        myObject[key][key2].data1;
        myObject[key][key2].data2;
        myObject[key][key2].date;
    }
}

答案 1 :(得分:0)

您可以通过调用方法

将json中的所有键名称作为数组获取
keys = Object.getOwnPropertyNames(jsonObj);

在您的示例中,这将返回一个数组['07', '08'],以从您可以调用的名称中获取实际对象:

keys.forEach((key) => {
    objects = Object.getOwnPropertyDescriptor(jsonObj, key)
})

然后你可以找到这些对象的键的名称并重复

objects.forEach((object) => {
    keys = Object.getOwnPropertyNames(object);
})