javascript 数组转换操作和格式化

92dk7w1h  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(106)

我有以下数组:

[
    {
        "level": "level3",
        "category": "car"
    },
    {
        "level": "level1",
        "category": "bike"
    },
    {
        "level": "level2",
        "category": "car"
    },
    {
        "level": "level5",
        "category": "bike"
    }
]

我需要将其转换为以下对象:

{
    car: ["level3", "level2"],
    bike: ["level1", "level5"],
}

实现这一目标的最佳途径是什么?先谢谢你了

yyyllmsg

yyyllmsg1#

你可以用很多方法来实现你想要的:

for...of方式

const data = [ { "level": "level3", "category": "car" }, { "level": "level1", "category": "bike" }, { "level": "level2", "category": "car" }, { "level": "level5", "category": "bike" } ];
const newObj = {};
for (const item of data) {
  const {level,category} = item;
  if (newObj[category]) {
    newObj[category].push(level);
  } else {
    newObj[category] = [level];
  }
}
console.log(newObj);

reduce方式

const data = [ { "level": "level3", "category": "car" }, { "level": "level1", "category": "bike" }, { "level": "level2", "category": "car" }, { "level": "level5", "category": "bike" } ];
const newObj = data.reduce((acc, item) => {
    const { level, category } = item;
    acc[category] = acc[category] || [];
    acc[category].push(level);
    return acc;
}, {});
console.log(newObj);

第一种方法简单易懂,第二种方法更实用。但是这两种方法都有O(n)的线性时间复杂度,选择其中一种只是个人偏好和编码风格的问题。

xpcnnkqh

xpcnnkqh2#

通过使用函数Array.prototype.reduce

const array = [{        "level": "level3",        "category": "car"    },    { "level": "level1",        "category": "bike"    },    {        "level": "level2",        "category": "car"    },    {      "level": "level5",        "category": "bike"    }],
      result = array.reduce((a, {level, category}) => {
        (a[category] = a[category] || []).push(level);
        return a;
      }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题