在数组上循环创建多个对象

4
所以我有一个存储每个用户爱好的数组,在对象内部的另一个数组中。
var hobbies = [
  {
    "id": 1,
    "hobbies": []
  },

  {
    "id": 2,
    "hobbies": [
      "football"
    ]
  },
  {
    "id": 3,
    "hobbies": [
      "football",
      "basketball"
    ]
  }
]

我希望你能将每个爱好单独拆成一个对象,并返回一个新的对象数组,格式如下。
var result = [
  {
    "id": 2,
    "hobby": "football"
  },
 {
    "id": 3,
    "hobby": "football"
  },
 {
    "id": 3,
    "hobby": "basketball"
  }
]

目前所拥有的是什么?
hobbies.filter((f, i) => f.hobbies.length > 0).map((p, i) => {
    while (i < p.hobbies.length) {
 return { id : p.id, hobby : p.hobbies[i] };
}
  });

只返回结果
[
  {
    "id": 2,
    "hobby": "football"
  },
  {
    "id": 3,
    "hobby": "basketball"
  }
]

看起来你在这里使用了关系型的方法。为什么这样做呢?Javascript不是一个关系型数据库,没有必要引用外部id。只需将hobbies属性附加到每个user对象上即可。 - connexo
5个回答

1
你可以使用 array#reducearray#map。遍历每个对象,然后遍历 hobbies 的每个爱好并创建对象。

var hobbies = [ { "id": 1, "hobbies": [] }, { "id": 2, "hobbies": [ "football" ] }, { "id": 3, "hobbies": [ "football", "basketball" ] } ],
    result = hobbies.reduce((r, {id, hobbies}) => r.concat(hobbies.map(hobby => ({id, hobby}))), []);
console.log(result);


1
这很符合我想要实现的目标,谢谢。 - Michaelh

1
我知道,“函数式”编程在这些领域被认为是“酷”的,但是,你考虑过使用简单的循环来循环遍历你的数据吗?
let result = [];

for (let {hobbies, id} of data)
    for (let hobby of hobbies)
        result.push({id, hobby})

在我看来,这比任何可能出现的reduce代码更易读;)

0

你需要使用内部循环来遍历爱好,逐个将它们推送到目标数组中:

var hobbies = [{
    "id": 1,
    "hobbies": []
  },

  {
    "id": 2,
    "hobbies": [
      "football"
    ]
  },
  {
    "id": 3,
    "hobbies": [
      "football",
      "basketball"
    ]
  }
];

var result = hobbies.reduce((acc, item) => {
  item.hobbies.forEach(hobby => {
    acc.push({
      id: item.id,
      hobby: hobby
    });
  });
  return acc;
}, []);

console.log(result);


0

您可以使用 Array.prototype.reduce

var hobbies = [{"id": 1,"hobbies": []},{"id": 2,"hobbies": ["football"]},{"id": 3, "hobbies": ["football","basketball"]}];

var res = hobbies.reduce((m, o) => (o.hobbies.forEach(h => m.push({id: o.id, hobby: h})), m), []);

console.log(res);


0
你需要嵌套循环,这是基础:
首先,你需要循环遍历主要的“hobbies”数组。
然后,对于数组中的每个项目(代表一个人),你想要循环遍历他们的爱好,并且对于每一个爱好,你需要将由个人资料ID和爱好组成的对象推入我之前创建的“results”数组。

var hobbies = [{ "id": 1, "hobbies": [] }, { "id": 2, "hobbies": [ "football" ] }, { "id": 3, "hobbies": [ "football", "basketball" ] } ];

let result = [];

hobbies.forEach(function(profile){
  profile.hobbies.forEach(function(hobby){
    result.push(
            {
        "id": profile.id,
        "hobby": hobby
      }
    );
  });
});

console.log(result)

更新:其他使用Array.reduce(一种更专业的循环)的答案将进一步缩短上述代码。

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