首页 > 解决方案 > 获取另一个数组中包含的所有单词(拆分句子)的数组

问题描述

我有这个数组:

this.places = [{"full_name":"joe","title1":"teacher","description":"the best teacher"},
              {"full_name":"mary","title1":"student","description":"great student"}];

我需要得到这个:

this.items = [{"word":"joe"},{"word":"teacher"},{"word":"the"},{"word":"best"},{"word":"teacher"}, 
             {"word":"mary"},{"word":"student"},{"word":"great"},{"word":"student"} ];

我现在有这个:

 this.places.forEach(item => {
        this.items = results.concat(item.full_name.toLocaleLowerCase().split(" "))
            .concat(item.title1.toLocaleLowerCase().split(" "))
            .concat(item.description.toLocaleLowerCase().split(" "));    
      });

结果:

["joe","teacher","the","best","teacher","mary","student","great","student"];

你能帮我得到完整的最终所需的数组吗?

标签: javascriptarraysjsonobject

解决方案


减少的另一种方法:

this.places = [
  {"full_name":"joe","title1":"teacher","description":"the best teacher"},             
  {"full_name":"mary","title1":"student","description":"great student"}
];

this.items = this.places.reduce((acc, place) => {
  Object.values(place).toString().split(/\s+|,/).forEach(word => acc.push({ word }));
  // This might be slightly faster
  // Object.values(place).toString().replace(/\w+/g, word => acc.push({ word }));
  return acc;
}, []);
console.log(this.items);


推荐阅读