Reputation: 966
I want to ask something which is actually I don't know what's wrong with my code. So, i've docs from database. Here is my docs :
{
"docs":[
{
"orderDate":{
"value":"2018-03-20",
"type":"date"
},
"name":{
"value":"Abid Rakhmansyah",
"type":"text"
},
"phone":{
"value":"082117414233",
"type":"number"
},
"email":{
"value":"[email protected]",
"type":"email"
},
"paid":{
"value":true,
"type":"boolean"
}
},
{
"orderDate":{
"type":"date",
"value":"2018-03-13T05:14:00.806Z"
},
"name":{
"value":"Iqbal Maulana",
"type":"text"
},
"phone":{
"value":"082117414233",
"type":"number"
},
"email":{
"value":"[email protected]",
"type":"email"
},
"paid":{
"type":"boolean",
"value":false
}
},
{
"orderDate":{
"value":"2018-03-20",
"type":"date"
},
"name":{
"value":"Abdullah",
"type":"text"
},
"phone":{
"value":"092034",
"type":"number"
},
"email":{
"value":"[email protected]",
"type":"email"
},
"paid":{
"value":true,
"type":"boolean"
}
},
{
"orderDate":{
"value":"2018-03-20",
"type":"date"
},
"name":{
"value":"asd",
"type":"text"
},
"phone":{
"value":"234234",
"type":"number"
},
"email":{
"value":"[email protected]",
"type":"email"
},
"paid":{
"value":true,
"type":"boolean"
}
},
{
"orderDate":{
"type":"date",
"value":"2018-03-20T06:01:54.821Z"
},
"name":{
"value":"as",
"type":"text"
},
"phone":{
"value":"082117414233",
"type":"number"
},
"email":{
"value":"[email protected]",
"type":"email"
},
"paid":{
"type":"boolean",
"value":false
}
}
],
"total":5,
"limit":8,
"page":1,
"pages":1
}
I want to get only value
property in the objects. So, i try to code like this.
orders.docs.forEach( function (arrayItem)
{
Object.keys(arrayItem.toJSON()).forEach(function(key) {
console.log(key, JSON.stringify(arrayItem[key].value));
});
});
I think that it will be work. But, I don't know why... The result of my code doesn't show like what I expected. Here is the result of my code :
[0] orderDate "2018-03-20"
[0] (node:20944) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'value' of undefined
For the first loop it work fine, but when it going to 2nd loop. The value
is undefined. What's is wrong?
Upvotes: 0
Views: 87
Reputation: 13860
Are you sure you're not just overthinking it?
Here's a Demo
I'm sure it could be cleaned up further, but without modifying your code too much this can find the key and value pairs just fine:
orders = JSON.parse( orders );
orders.docs.forEach( function( arrayItem ){
Object.keys(arrayItem).forEach( function(key) {
console.log( key +': '+ arrayItem[key].value );
});
});
Upvotes: 1