Javascript sum values in 3 objects

Hi I'm trying to sum the values I have in 3 json objects.

var things = {
    "noun": {
        "syn": ["belongings", "holding", "stuff", "property"]
    }
};
var stuff = {
    "noun": {
        "syn": ["belongings", "holding", "property"]
    }
};
var crap = {
    "noun": {
        "syn": ["things", "holding", "waste"]
    }
};

result = {};
word1 = things.noun.syn
for (key in word1) {
    nk = word1[key];
    if (result.nk == undefined) {
        result.nk = 1
    } else {
        result.nk = result.nk + 1;
    }
}
console.log(result);‚Äč

The result I am getting is result.nk instead of result.belongings for example.

I've been screwing around in a jsfiddle: http://jsfiddle.net/qunUz/2/

How do I sum the amount of times each value appears?

Answers


To access a property given a string value you should use bracket notation

result[nk] //access the property defined by nk's value

instead of the dot notation you are using

result.nk     //access the 'nk' property
result['nk']  //equivalent in bracket notation.

By setting result.nk you are not using the variable nk but really result.nk.

You should store it like this:

result[nk] = 1;

Like demonstrated on the updated fiddle: http://jsfiddle.net/qunUz/3/


I think this is what you are trying to do. The following will sum up the occurrences of each value in your three different arrays.

var a = things.noun.syn.concat(stuff.noun.syn).concat(crap.noun.syn);
var a = a.reduce(function (acc, curr) {
  if (typeof acc[curr] == 'undefined') {
    acc[curr] = 1;
  } else {
    acc[curr] += 1;
  }

  return acc;
}, {});

Results in

belongings: 2
holding: 3
property: 2
stuff: 1
things: 1
waste: 1

If your target browser doesn't have a reduce function, you can use underscore.js (or just copy their reduce function).


Need Your Help

Observe all functions being called in an application

java rmi xml-rpc observer-pattern

I am starting out to build a remote collaboration application.