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

时间:2018-03-01 11:49:54

标签: javascript ecmascript-6

所以我有一个数组,用于存储对象中数组中每个用户的爱好..

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"
  }
]

5 个答案:

答案 0 :(得分:1)

您可以将sizearray#reduce一起使用。遍历每个对象,然后遍历array#map的每个爱好并创建对象。

&#13;
&#13;
hobbies
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我知道,&#34;功能性&#34;编程被视为&#34;酷&#34;但是,围绕这些部分,您是否考虑过使用简单的循环来循环数据?

let result = [];

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

在我看来,这比任何人可能提出的reduce意大利面更具可读性;)

答案 2 :(得分:0)

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

&#13;
&#13;
*   Trying 130.211.169.89...
* TCP_NODELAY set
* Connected to my.wirelesstag.net (130.211.169.89) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=my.wirelesstag.net
*  start date: Jul 20 00:00:00 2017 GMT
*  expire date: Oct 19 23:59:59 2019 GMT
*  subjectAltName: host "my.wirelesstag.net" matched cert's "my.wirelesstag.net"
*  issuer: C=US; O=GeoTrust Inc.; CN=RapidSSL SHA256 CA
*  SSL certificate verify ok.
> POST /ethAccount.asmx/SignIn HTTP/1.1
Host: my.wirelesstag.net
Accept: */*
Content-Type: application/json
Content-Length: 58

* upload completely sent off: 58 out of 58 bytes
< HTTP/1.1 500 Internal Server Error
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: application/json; charset=utf-8
< Expires: -1
< Server: Microsoft-IIS/8.5
< jsonerror: true
< Date: Thu, 01 Mar 2018 11:27:33 GMT
< Content-Length: 1019
< 
* Connection #0 to host my.wirelesstag.net left intact
Error: Internal Server Error
&#13;
&#13;
&#13;

答案 3 :(得分: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);

答案 4 :(得分:0)

您需要嵌套循环,这是它的基础:

首先需要遍历主hobbies数组。

然后对于数组中的每个项目(代表一个人),你想要遍历他们的爱好,并且对于每个爱好,你需要将由个人资料ID和爱好组成的对象推送到{我之前创建的{1}}数组。

&#13;
&#13;
results
&#13;
&#13;
&#13;

更新:使用Array.reduce(一个更专业的循环)的其他答案将进一步削减上面的代码。