【问题标题】:How to use Object.keys()?如何使用 Object.keys()?
【发布时间】:2017-11-19 19:52:44
【问题描述】:

我通常习惯于使用 Object.keys() 函数。 但是这一次,对于以下 JSON 中的每个对象,我无法按名称读取属性的值:

JSON

var myData = {
  "customNotes":{
    "2017/04/17":{
      "concernedDate":"April, 17, 2017",
      "notesList":[
        {
          "id":25,
          "title":"Note 25 Title"
        },
        {
          "id":51,
          "title":"Note 51 Title"
        }
      ]
    },
    "2017/04/14":{
      "concernedDate":"April, 14, 2017",
      "notesList":[
        {
          "id":53,
          "title":"Note 53 Title"
        }
      ]
    }
  }
}

我需要的输出

我需要的是以下输出:

    2017/04/17
    concernedDate: April, 17, 2017
    Number of notes: 2
    Notes list:
    - id: 25
    - title: Note 25 Title
    - id: 51
    - title: Note 51 Title
    - - - - - - - -
    2017/04/14
    concernedDate: April, 14, 2017
    Number of notes: 1
    Notes list:
    - id: 53
    - title: Note 53 Title

我的错误 JS 代码

$(Object.keys(myData.customNotes)).each(function(iGroup){

    //Get Key/Val of each Group of notes
    var keyGroup = Object.keys(myData.customNotes)[iGroup];
    var valGroup = myData.customNotes[keyGroup];

    //Print Key (the date as a string)
    console.log(valGroup[0]);

    //Print Key Property ('concernedDate')
    console.log('concernedDate: ' + valGroup[0].concernedDate);

    //Print Key Property Length ('notesList')
    console.log('Number of notes: ' + valGroup[0].notesList.length);

    //Print List of notes
    console.log('Notes list:');

    //If the property exists
    if(valGroup[0].notesList){
        //For each item in 'notesList'
        $(Object.keys(valGroup[0].notesList)).each(function(iNote){

            //Get Key/Val For each note
            var keyNote = Object.keys(valGroup[0].notesList)[iNote];
            var valNote = valGroup[0].notesList[keyNote];

            //Print the properties of each note
            console.log('- id: ' + valNote.id);
            console.log('- title: ' + valNote.title);
        });
    }

});

【问题讨论】:

    标签: arrays json for-loop foreach javascript-objects


    【解决方案1】:

    排序

    在我的对象中添加了一些元素后,我需要按 KEY 对其进行排序(日期:例如 2017/04/17)。

    但无论我尝试什么,它总是以相同的顺序返回相同的项目:

    //Creating an Array of SORTED values (Nothing works :-/)
    var tmpArr = Object.keys(myData.customNotes).sort((a, b) => a > b ? a : b);
    var tmpArr = Object.keys(myData.customNotes).sort((a, b) => Date(a).valueOf() > Date(b).valueOf() ? a : b);
    var tmpArr = Object.keys(myData.customNotes).sort((a, b) => a.valueOf() > b.valueOf() ? a : b);
    var tmpArr = Object.keys(myData.customNotes).sort((a, b) => a-b);
    
    
    //Convert back the Array to an Object
    var myData.customNotes = tmpArr.reduce(function(acc, cur, i) {
      acc[i] = cur;
      return acc;
    }, {});
    

    【讨论】:

    • 我不在电脑旁,但您可以尝试删除传递给 sort 的回调,然后像 sort() 一样调用它
    • 抱歉之前的语法错误,混淆w/reduce!还忘了提到,如果您没有对其进行变异并且可以在某个地方访问它,那么您不必经历所有这些减少的东西。无论如何这对我有用: Object.keys(myData.customNotes).sort((a, b) => new Date(a) new Date(b) ? 1 : 0).map(k => myData.customNotes[k]);
    • @cheestherapy :谢谢:这对数组非常有效 :) 我选择打开一个新帖子来更具体地介绍这个排序主题。结果是我得到了一个令人满意的解决方案,让我可以坚持使用 Object,而不必处理 Array。仅供参考,可以在这里找到:stackoverflow.com/questions/44611392/…
    【解决方案2】:

    首先,我要感谢@cheestherapy 的回答:它就像一个魅力,你绝对应该依赖它,无论它是在 ES6 还是 ES5 中!

    同时,我自己进行了实验,发现另一种可行的解决方案,以更“经典的循环风格”方式实现结果相同

    另一种工作方法(更经典)

    因此,对于那些希望在脚本的每一步拥有更多控制权的人来说,这里是另一种可行的方法

    //WORKING
    console.log('---START LIST---');
    
    //For each GROUP OF NOTES
    for (var item in myData.customNotes) {
        //Print GROUP OF NOTES key
        console.log(item);
    
        //Print GROUP OF NOTES properties
        console.log('concernedDate: ' + myData.customNotes[item].concernedDate);
        console.log('Number of notes: ' + myData.customNotes[item].notesList.length);
        console.log('Notes list: ');
    
        //For each NOTE
        $(Object.keys(myData.customNotes[item].notesList)).each(function(iGroup){
    
            //Get this Array item
            var keyGroup = Object.keys(myData.customNotes[item].notesList)[iGroup];
            var valGroup = myData.customNotes[item].notesList[keyGroup];
    
            //Print NOTE properties
            console.log('- id: ' + valGroup.id);
            console.log('- title: ' + valGroup.title);
    
        });
        console.log('- - - - - -');
    
    }
    console.log('---END LIST---');
    

    【讨论】:

      【解决方案3】:

      es6

      Object.keys(myData.customNotes).reduce((prev, curr) => {
          const date = curr;
          const concernedDate = myData.customNotes[curr].concernedDate;
          const numberNotes = myData.customNotes[curr].notesList.length;
          const notesList = myData.customNotes[curr].notesList.map(note => `- id: ${note.id} \n - title: ${note.title} \n\n`);
      
          return prev + `${date} \n ${concernedDate} \n Number of notes: ${numberNotes} \n Notes list: \n ${notesList} \n - - - - - - - - \n`;
         }, ''));
      

      es5

      Object.keys(myData.customNotes).reduce(function (prev, curr) {
          const date = curr;
          const concernedDate = myData.customNotes[curr].concernedDate;
          const numberNotes = myData.customNotes[curr].notesList.length;
          const notesList =        myData.customNotes[curr].notesList.map(function(note) { return  ‘- id: ‘ +  note.id + ‘\n’ + ‘- title: ‘ + note.title + ‘\n\n’;});
      
          return prev + 'date' +  '\n' + concernedDate +  '\n Number of notes: ' + numberNotes +  '\n Notes list: \n' + notesList + ' \n - - - - - - - - \n';
      }, ''));
      

      【讨论】:

      • 嗨@cheestherapy,谢谢。看来我最新的 Firefox 不接受这种语法。它返回:SyntaxError: missing ; before statement?我不习惯这种现代的`=> 运算符。你能用更“经典”(和更长)的方法吗?
      • 我刚刚编辑它以包含 ES5。 "`" 用于模板文字,因此您不必连接更大的字符串。
      • 非常感谢@cheestherapy:您的 ES6 和 ES5 版本都可以正常工作。事实上,reduce() 函数末尾有一个多余的括号导致了SyntaxError: missing ; before statement 错误。 :-)(我已经编辑了您的答案以使其 100% 正确。非常感谢您向我解释避免我连接长字符串的模板函数:太棒了!
      • 只是一个问题:在我的数组中动态添加了一些元素后,我将如何继续按日期对myData.customNotes 进行排序?并为每个子项做同样的事情(按相关日期排序)?
      • 嗯,在 JS 中你不能保证对象中键/值对的存储顺序,所以数组是你最好的选择!数组还有一个内置的排序方法,它接受一个回调,该回调接受两个参数,以某种方式比较它们,然后返回你希望返回到开头的那个。但是,如果有其他因素使您倾向于对象格式,并且您只需要在一个地方对其进行排序,您总是可以映射自定义注释的 object.keys(返回数组),对其进行排序,然后归约回一个对象
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2022-11-14
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多