Javascript在3个对象中求和值
嗨,我正在尝试对3个json对象中的值求和Javascript在3个对象中求和值,javascript,arrays,json,object,Javascript,Arrays,Json,Object,嗨,我正在尝试对3个json对象中的值求和 var things = { "noun": { "syn": ["belongings", "holding", "stuff", "property"] } }; var stuff = { "noun": { "syn": ["belongings", "holding", "property"] } }; var crap = { "noun": { "sy
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);
我得到的结果是result.nk
,而不是result.properties
我一直在胡闹:
如何计算每个值出现的次数之和?要访问给定字符串值的属性,应使用括号表示法
result[nk] //access the property defined by nk's value
而不是您正在使用的点符号
result.nk //access the 'nk' property
result['nk'] //equivalent in bracket notation.
通过设置result.nk,您使用的不是变量
nk
,而是真正的result.nk
您应该这样存储它:
result[nk] = 1;
就像在更新的小提琴上演示的那样:我认为这就是你想要做的。下面将总结三个不同数组中出现的每个值
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;
}, {});
导致
belongings: 2
holding: 3
property: 2
stuff: 1
things: 1
waste: 1
如果您的目标浏览器没有reduce函数,您可以使用underline.js(或者只复制它们的reduce函数)。btw,您不应该使用for in循环来迭代数组。改用常规for循环或forEach方法。@missingno我以为你应该用for for对象?(它不是数组)。我错了吗?嗯,在你写的代码中,
word1
是一个数组。。。