javascript NodeJS中JSON的字数统计[重复]

ktca8awb  于 2022-12-10  发布在  Java
关注(0)|答案(1)|浏览(142)

此问题在此处已有答案

Counting the occurrences / frequency of array elements(39个答案)
13个小时前关门了。
我有一个这样的物体

{
"value": ["aaa", "bbb", "ccc", "aaa"], 
"answer": ["lorem", "lorem", "lorem", "lorem"], 
"question": ["lorem", "lorem", "lorem", "lorem"]}
}

如何从属性值中获取字数?
我尝试使用reduce()

const countedNames = query.reduce((allNames: any, name: any) => {
      const currCount = allNames[name.value] ?? 0;
      return {
        ...allNames.value,
        [name.value]: currCount + 1,
      };
    }, {});

但是我没有得到我所期待的结果
我期待的结果是这样的

{
"aaa": 2,
"bbb": 1,
"ccc": 1
}
m1m5dgzv

m1m5dgzv1#

reduce应直接用于数组query.value,而不是用于父对象

const query = {
  "value": ["aaa", "bbb", "ccc", "aaa"],
  "answer": ["lorem", "lorem", "lorem", "lorem"],
  "question": ["lorem", "lorem", "lorem", "lorem"]
}

const countedNames = query.value.reduce((allNames, name) => {
  const currCount = allNames[name] ?? 0;
  return {
    ...allNames,
    [name]: currCount + 1,
  };
}, {});

console.log(countedNames);

相关问题