Manish Sharma
Manish Sharma

Reputation: 93

why property get added as variable rather than its actual value in the object?

Assume

const words = ["hello", "this", "is", "hello", "this", "anything"]

let wordcount = {};
words.forEach((w) => {
  if (wordcount[w]) {
    wordcount.w = wordcount.w++;
  } else {
    wordcount.w = 1;
  }
})
console.log(wordcount)

my expected output should be

{hello:2,this:2,is:1,anything:1}

Instead I am getting this-

{w:1}

why w get added as property instead of its value.

Upvotes: 1

Views: 62

Answers (2)

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17570

let y="test";

//While you use data.y then it means you create or update  attribute with key y
var data={};
data.y=5;
console.log(data);

//While you use data[y] it means you create or update  attribute with key as value of y
data[y]=2;
console.log(data);

so you use wordcount[w] rather than wordcount.w

words=["hello","this","is","hello","this","anything"]
let wordcount={};
words.forEach((w)=>{  
    if(wordcount[w])
    {
      wordcount[w]++;
    }
    else{
         wordcount[w]=1;
    }
})
console.log(wordcount)

Upvotes: 1

0brine
0brine

Reputation: 486

use this:

let words = ["hello", "this", "is", "hello", "this", "anything"];
let wordCount = {};

words.forEach(w => {
  if (wordCount[w] == undefined) wordCount[w] = 1;
  else wordCount[w]++;
})
console.log(wordCount)

Upvotes: 0

Related Questions