列出字典列表中的值

问题描述 投票:2回答:2
var dicList = [{
  student_id: 334,
  full_name: "student B",
  score: 9,
  class_id: 222
}, {
  student_id: 333,
  full_name: "student A",
  score: 7,
  class_id: 222
}]

for (var i = 0; i++; i < dicList.length) {
  for (var key in dicList[i]) {
    if (test.hasOwnProperty(key)) {
      console.log(key, dicList[i][key]);
    }
  }
}

当前返回undefined,我希望它返回每个字典中每个属性的值列表

javascript
2个回答
1
投票

你需要

  • 最后两个部分,conditionfinal-expression部分for statement,和 for ([initialization]; [condition]; [final-expression]) statement
  • 检查dicList[1]而不是test

var dicList = [{ student_id: 334, full_name: "student B", score: 9, class_id: 222 }, { student_id: 333, full_name: "student A", score: 7, class_id: 222 }]

for (var i = 0; i < dicList.length; i++) {     // move i++ to the end
    for (var key in dicList[i]) {
        if (dicList[i].hasOwnProperty(key)) {  // use dicList[i] instead of test
            console.log(key, dicList[i][key]);
        }
    }
}

2
投票

您可以使用flatMap()Object.entries()以及forEach()迭代结果数组。

Array.prototype.flatMap = function(f){
  return [].concat(...this.map(f))
}
var dicList = [{student_id: 334,  full_name: "student B",  score: 9,  class_id: 222}, {  student_id: 333,  full_name: "student A",  score: 7,  class_id: 222}]

const res = dicList.flatMap(Object.entries)
res.forEach(([key,value]) => console.log(`key:${key} value:${value}`));

qazxsw poi不适用于所有浏览器,所以你使用qazxsw poi并创建嵌套的flatMap()

您还可以为forEach()创建polyfill

var dicList = [{student_id: 334,  full_name: "student B",  score: 9,  class_id: 222}, {  student_id: 333,  full_name: "student A",  score: 7,  class_id: 222}]

const res = dicList.map(Object.entries)
res.forEach(a => a.forEach(([key,value]) => console.log(`key:${key} value:${value}`)));
Array.prototype.flatMap = function(f){
  return [].concat(...this.map(f))
}
© www.soinside.com 2019 - 2024. All rights reserved.