array as its value? 如何将字符串的数组的数组转换为一个对象,其中每个字符串都是一个包含下一个数组作为值的对象的键?

3

我有一个像这样格式化的数组

const array = [
  ['technology', 'apple', 'computers', 'macbook_pro'],
  ['technology', 'apple', 'computers', 'macbook_air'],
  ['technology', 'apple', 'phones', 'iphone'],
  ['technology', 'samsung', 'phones', 'Galaxy S21'],
]

我需要将它转换为以下格式的对象:

{
  technology: {
    apple: {
      computers: {
        macbook_pro: {},
        macbook_air: {}
      },
      phones: {
        iphone: {}
      }
    },
    samsung: {
      phones: {
        galaxy_s21: {}
      }
    }
  }
}

我尝试使用两个forEach循环完成它,但总是卡住。


你知道数组的大小始终为4 ([4][])吗?还是这是一个将矩阵转换成图形的通用问题? - azbarcea
2个回答

2
使用 Array#reduce,遍历数组并更新一个对象累加器。
在每次迭代中,将当前累加器设置为current,并使用 Array#forEach 遍历当前列表。如果 current 没有属性,则使用 nullish operator 将值设置为{}。然后将 current 重置为下一次迭代中使用的值。

const array = [
  ['technology', 'apple', 'computers', 'macbook_pro'],
  ['technology', 'apple', 'computers', 'macbook_air'],
  ['technology', 'apple', 'phones', 'iphone'],
  ['technology', 'samsung', 'phones', 'Galaxy S21'],
];

const res = array.reduce((acc, props) => {
  let current = acc;
  props.forEach(prop => {
    current[prop] ??= {};
    current = current[prop];
  });
  return acc;
}, {});

console.log(res);


使用 ??= 表示逻辑空值赋值 - sp00m
1
传奇,非常感谢您提供的代码,更感谢您清晰的解释。逻辑空值赋值也很有趣。我以前没见过。祝一切顺利! - ilrock

1

Array.reduce 的实现如下所示:

  • 遍历输入的 array
  • 遍历输入数组中的每个节点。
  • 检查累加器是否具有该键的节点。
  • 如果没有,则在累加器中创建一个空对象作为该节点。
  • 将新创建的节点或现有节点保留为临时值。
  • 此临时变量在循环中不断深入您的累加器对象。

const array = [
  ['technology', 'apple', 'computers', 'macbook_pro'],
  ['technology', 'apple', 'computers', 'macbook_air'],
  ['technology', 'apple', 'phones', 'iphone'],
  ['technology', 'samsung', 'phones', 'Galaxy S21'],
]
const output = array.reduce((acc, curr) => {
  let temp = acc;
  curr.forEach((node) => {
    if (!temp[node]) {
      temp[node] = {}
    }
    temp = temp[node]
  })
  return acc;
}, {});
console.log(output)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接