Ashvini Kumar
Ashvini Kumar

Reputation: 107

How to add properties dynamically in the object in javascript?

I want to know that how many times each alphabet comes in the 'input' variable. For this I am loop through each character and storing them in an object and also how many they appeared in the sentence. But It is consoling NaN. Please show me where is the error?

var input = "why this kolaveri kolaveri di";
function processData(input) {
    var object = {};
    input.replace(/\s/g,"").split("").forEach(function(item){
        object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;
    });
    console.log(object);
} 

Upvotes: 1

Views: 48

Answers (3)

Kishore Sahasranaman
Kishore Sahasranaman

Reputation: 4230

You had the problem in the below line of code .

object[item] == 'undefined' ? object[item] = 0 && object[item]++ : object[item]++ ;

Update Code:

var input = "why this kolaveri kolaveri di";
function processData(input) {
    var object = {};
    input.replace(/\s/g,"").split("").forEach(function(item){
        if(object[item] == null)
        { 
            object[item] = 0;
            object[item]++; 
        }else{
            object[item]++;
        }
    });
    console.log(object);
}

//testing here 
processData(input);

Upvotes: 0

This work

  typeof object[item] == 'undefined' ?

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116190

You can use hasOwnProperty to check if a property exists.

var input = "why this kolaveri kolaveri di";


var object = {};
input.replace(/\s/g,"").split("").forEach(function(item){
  
  // If the property doesn't exist, initialize it to 0
  if (!object.hasOwnProperty(item))
    object[item] = 0;
  
  object[item]++
});
console.log(object);
 

For the haters, you can initialize to 1 and only increment in the else. Essentially the same but a few cycles more efficient. Use whichever you think looks best.

  // If the property doesn't exist, initialize it to 1
  if (!object.hasOwnProperty(item))
    object[item] = 1;
  else
    object[item]++;

Upvotes: 1

Related Questions