1

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?

3
  • btw, you should not use for-in loops to iterate over arrays. Use a regular for loop or the forEach method instead. Commented Apr 17, 2012 at 23:23
  • @missingno i thought you were supposed to use for-in for objects? (its not an array). Am i wrong? Commented Apr 17, 2012 at 23:27
  • Well, in the code you wrote word1 is an array... Commented Apr 17, 2012 at 23:47

3 Answers 3

1

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.
Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.