访问对象属性

时间:2017-04-27 15:09:46

标签: javascript

我有一个JSON文件,其中包含一个名为dateOfBirth的属性,并且大多数对象具有不同的格式(例如:一个具有1.9.2012,另一个具有02.04.1929)。我编写了一个函数,它将日期格式更改为在每个对象中都相同,但是我将它连接到数组时失败了。我究竟做错了什么?怎么修好?它必须在纯Javascript中完成,不需要jQuery或任何框架。



const endpoint = 'https://api.myjson.com/bins/agowj';
const people = [];
fetch(endpoint)
    .then(blob => blob.json())
    .then(data => people.push(...data));


people.dateOfBirth.forEach(function(elem) {

    var newtab = [];
    elem.split("-").forEach(function(elemi) {
        if (elemi.length === 1) {
            newtab.push("0" + elemi);
        } else {
            newtab.push(elemi);
        }
    })
    console.log(newtab.join("-"));
})




1 个答案:

答案 0 :(得分:0)

你需要解析people.dateOfBirth成功回调你的api电话。现在你的代码逐行执行,当涉及到people.dateOfBirth.forEach你的people变量仍然是一个空数组。

    const endpoint = 'https://api.myjson.com/bins/agowj';
    const people = [];
    fetch(endpoint)
        .then(blob => blob.json())
        .then((data) => {
            people.push(...data);
            people.forEach((person) => {
              var newtab = [];
              person.dateOfBirth.split("-").forEach(function(elemi) {
                if (elemi.length === 1) {
                    newtab.push("0" + elemi);
                } else {
                    newtab.push(elemi);
                }
                 console.log(newtab.join("-"));
              })
             })
         });


    

<!-- end snippet -
<!-- begin snippet: js hide: false console: true babel: false -->