javascript - 从对象键构建字符串

标签 javascript arrays string object reduce

我有一个带有键和值的对象。每个值都是一个数组,用于描述键在字符串中的位置。

 const input = {
  ' ': [5],
  d: [10],
  e: [1],
  H: [0],
  l: [2,3,9],
  o: [4,7],
  r: [8],
  w: [6],
};

const buildString = (m) => {
 
}
我注意返回字符串 Hello world 。我的解决方案如下所示:
const buildString = (m) => {
  let res = [];
  for(let key in m) {
    m[key].map(el => {
      res[el] = key;
    })
  }
  return res.join('');
}
但我想可以使用 解决它减少 方法。有人可以帮我实现吗?
提前致谢。

最佳答案

你去吧

const input = {
  ' ': [5],
  d: [10],
  e: [1],
  H: [0],
  l: [2,3,9],
  o: [4,7],
  r: [8],
  w: [6],
};
const words = Object.entries(input)
  .reduce( (acc, [character, positions]) => {
    //      |     ^ Object.entries gives you an array of [key, value] arrays
    //      ^ acc[umulator] is the array (second parameter of reduce)
    positions.forEach(v => acc[v] = character);
    //        ^ put [character] @ the given [positions] within acc
    return acc;
  }, [])
  .join("");
// ^ join the result to make it a  a string

console.log(words);

关于javascript - 从对象键构建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66368016/

相关文章:

javascript - jquery 中的文本框验证

javascript - 当参数是函数时,jQuery 切换不起作用

java - 带有自己类的 NullPointerException

string - 按字面意思将字符串转换为字节

r - 如何用R中的条件替换前两个匹配模式

javascript - 单击内部按钮时防止单击父 A 标记

c++ - 将一个对象中的数组设置为等于另一个对象中的数组?

php - 使用php以一种形式将两个数组发送到mysql

C++ 在数组中搜索字符串

javascript - 使用 getDerivedStateFromProps 获取 API 数据导致组件渲染多次