I have the below object:
Configs = {};
Configs['category'] = [];
Configs['category']['prod1'] = [];
Configs['category']['prod1'].hosts ={
'table': {
'count': 'total_remaining',
'specs': [
{
'name': 'Test 1',
'code': 'BrandName.Cat.Code.[X].Price'
}
]
}
};
I am trying to create an array of elements to be requested from the database using the code below:
var data = Configs["category"]["prod1"].hosts.table;
var count = [data.count];
var names = data.specs;
var namesArray = names.map(function(names) {
var str = names['code'];
var requiredPortion = str.split("[X]");
var newStr = requiredPortion[0];
return newStr;
});
requestData = namesArray.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]); //remove duplicates
requestData.push(count);
console.log(count);
console.log(requestData);
The desired output is:
["BrandName.Cat.Code.", "total_remaining"]
But, when executing my code I am getting the following output:
["BrandName.Cat.Code.", Array[1]]
I am attaching a fiddle link for this. I guess the issue is with array push function usage. Please help.
asked Dec 31, 2015 at 6:36
user4571995
-
Your fiddle link seems to be workingMiguel– Miguel2015年12月31日 06:46:48 +00:00Commented Dec 31, 2015 at 6:46
-
Was doing a trial and error. Just noticed I got it.user4571995– user45719952015年12月31日 06:52:10 +00:00Commented Dec 31, 2015 at 6:52
2 Answers 2
You just have to remove the square bracket outside the count variable initialization. Try:
var count = data.count;
Instead of:
var count = [data.count];
Fiddle updated.
answered Dec 31, 2015 at 6:37
Abhijith Sasikumar
15.3k4 gold badges34 silver badges46 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Replace var count = [data.count]; with count = Object.keys(data).length
Maybe this helps.
answered Dec 31, 2015 at 6:51
Sandeep Sharma
1,8853 gold badges21 silver badges34 bronze badges
4 Comments
Sandeep Sharma
It may be another alternative because I tried with node.js' console, there var count = Object.keys(data).length works but var count = data.count; does not work.
lang-js