提问者:小点点

用javascript动态创建和填充数组


拥有编程语言数组,如:nbsp;

const tags = ["js", "ruby", "ios", "python", "go"];

我还有一个用户列表,比如: ;

const user = [
  {
    "id": "userId_1",
    "language": ["ruby", "ios"]
  }, 
  ...
];

有没有一种很好的方法用用户的ID填充由语言名称命名的数组?

类似: ;

const ruby = ["userId_1", "userId_3", "userId_8", ...];

共2个答案

匿名用户

可以使用Array.Reduce()。

null

const tags = ["js", "ruby", "ios", "python", "go"];

const user = [
  {
    "id": "userId_1",
    "language": ["ruby", "ios"]
  }, 
  {
    "id": "userId_2",
    "language": ["ruby", "python"]
  }, 
  {
    "id": "userId_3",
    "language": ["go", "ios"]
  }, 
];

const output = user.reduce((acc, cur) => {
  cur.language.forEach(lang => {
    if (!acc[lang]) acc[lang] = [];
    acc[lang].push(cur.id);
  });
  return acc;
}, {});

console.log(output);

匿名用户

短一点的会更好:

const ruby = user.map((user) => user.language.includes("ruby") ? user.id : undefined);