user4571995
user4571995

Reputation:

javascript array push issue

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.

Upvotes: 1

Views: 607

Answers (2)

Sandeep Sharma
Sandeep Sharma

Reputation: 1885

Replace var count = [data.count]; with count = Object.keys(data).length

Maybe this helps.

Upvotes: 0

Abhijith Sasikumar
Abhijith Sasikumar

Reputation: 14980

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.

Upvotes: 5

Related Questions