I have an array like
{
"Count": 3,
"Items": [
{
"prod_price": {
"N": "100"
},
"prod_name": {
"S": "Laptop"
},
"prod_Id": {
"N": "3"
}
},
{
"prod_price": {
"N": "1000"
},
"prod_name": {
"S": "Mouse"
},
"prod_Id": {
"N": "2"
}
},
{
"prod_price": {
"N": "2000"
},
"prod_name": {
"S": "Keyboard"
},
"prod_Id": {
"N": "1"
}
}
],
"ScannedCount": 3
}
I need the output like
{
"Count": 3,
"Items": [
{
"prod_price" : "100",
"prod_name": "Laptop",
"prod_Id": "3"
},
{
"prod_price" : "1000",
"prod_name": "mouse",
"prod_Id": "2"
},
{
"prod_price" : "2000",
"prod_name": "keyboard",
"prod_Id": "1"
},
],
"ScannedCount": 3
}
I am trying to get this output but no able to get this can you help me for this.
var items=data['Items'];
var itemresult={};
itemvalues={};
for(var attributename in items){
for(var itemattribute in items[attributename]){
for(var key in items[attributename][itemattribute]){
console.log(itemvalues);
itemresult.attributename.itemattribute=items[attributename][itemattribute][key];
}
}
I am new to node.js and don't how to work with the for loops exactly. I have tried my best, as if in php we have the for-each loop so we can skip the index value.
If I can get that so this conversion will be done. I don't know how to get that, can you please help me to find the solution?
I know there can be some problem because I don't know the exact syntax so any help would be appreciated. Thank you
t.niese
41k9 gold badges78 silver badges111 bronze badges
asked Aug 11, 2015 at 7:36
Bhavik Joshi
2,6978 gold badges28 silver badges50 bronze badges
-
why just not to use Array.map, it's both browser/nodejs; or some of the lodash.com toolboxshershen– shershen2015年08月11日 07:47:15 +00:00Commented Aug 11, 2015 at 7:47
-
1As a note: This is not related to node but a regular JavaScript question (I know this is somehow nit picking, but you should always be clear about what it language and what it platform specific) . Beside that you should take care what kind of loop you use for which kind of object. Why is using "for...in" with array iteration such a bad idea?.t.niese– t.niese2015年08月11日 07:48:02 +00:00Commented Aug 11, 2015 at 7:48
1 Answer 1
var items = data['Items'];
var result = [];
items.forEach(function(item) {
result.push({
prod_price: item.prod_price.N,
prod_name: item.prod_name.S,
prod_Id: item.prod_Id.N
});
});
Optionally you could use .map:
var result = items.map(function(item) {
return {
prod_price: item.prod_price.N,
prod_name: item.prod_name.S,
prod_Id: item.prod_Id.N
};
});
answered Aug 11, 2015 at 7:46
Alex Booker
10.9k4 gold badges28 silver badges37 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
mfeineis
It should be noted that this is only working in environments that support ES5 Array#forEach or Array#map
Alex Booker
@vanhelgen Yep. The question is tagged Node so I think he'll be OK. Well worth pointing out, though.
mfeineis
Ahh, fair enough. I glanced over this - but at least it's not wrong g
lang-js