I have been searching for answers to this for awhile and can’t seem to see the obvious.
I’m attempting to return the value by index of a json string. Although the key appears to match, its returning -1 for index. I simply want the value, in this case “Ethan” for key username. I’ve verified that rows is valid json.
for (var r in rows) {
table_body += '<tr>';
for (var c in cols) {
table_body += '<td>';
//table_body += Object.keys(rows[r]);
var idx = c;
console.log(rows[r]);
var o = rows[r]; //the object
//var key = Object.keys(o)[idx];
var key = cols[c].title;
var index = Object.keys(cols).indexOf(key);
console.log('key: '+key);
console.log('index: ' + index);
console.log('cols: ');
console.log(cols[c]);
console.log('c: ' + c);
var value = o[index];
table_body += value;
table_body += '</td>';
}
table_body += '</tr>';
}
table_body += '</table>';
This is the output in the console showing “o”, which is the json, the key, which is username, and the index of that key, -1
EDIT
This is the json for rows…
[{"id":136,"userName":"ethan","halfDays":1,"fullDays":11,"approvedDept":null,"approvedExec":true,"type":"vacation","createDate":"/Date(1332863557393)/","approvedDeptDate":null,"approvedExecDate":null,"leaveBegin":"/Date(1311570000000)/","leaveEnd":"/Date(1311570000000)/","notes":"Beginning Balance","overage":false,"department":null,"reminderSent":true},{"id":381,"userName":"ethan","halfDays":0,"fullDays":1,"approvedDept":null,"approvedExec":true,"type":"sick","createDate":"/Date(1336055792800)/","approvedDeptDate":null,"approvedExecDate":"/Date(1336021200000)/","leaveBegin":"/Date(1335502800000)/","leaveEnd":"/Date(1335502800000)/","notes":null,"overage":false,"department":"Marketing","reminderSent":true}]
and cols…
[{ "title":"userName" },{ "title":"leaveBegin" },{ "title":"leaveEnd" }]
3
Answers
It looks like, you want to find index in array of objects. Use findIndex:
cols
is an array of objects,Object.keys()
just returns an array of the array indexes, not the values of thetitle
properties of the objects.Use
findIndex()
to search for a matching object.Alternatively, before the loops you could create an object that maps all the keys to their indexes, and use that.
Then in the loop you would do
To get the corresponding value to some field, consider the simpler example involving a dumb row:
consider the col:
you would get the value associated to username with
now the array cols:
Finally for each row: