Reputation: 61
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]);
}
}
}
currently returns undefined, I want it to return a list of the values for each attribute in each dictionary
Upvotes: 2
Views: 66
Reputation: 36564
You can use flatMap()
and Object.entries()
and forEach()
iterate through result array.
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}`));
flatMap()
doesnot work in all browsers so you use map()
and create nested forEach()
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))
}
You can also create polyfill for flatMap()
if(!Array.prototype.flatMap){
Array.prototype.flatMap = function(f){
return [].concat(...this.map(f))
}
}
Upvotes: 2
Reputation: 386570
You need to
swich the last two parts, condition
and final-expression
part of the for
statement, and
for ([initialization]; [condition]; [final-expression])
statement
check dicList[1]
instead of 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]);
}
}
}
Upvotes: 1