简体   繁体   中英

Making one to many relation array in JavaScript

I have two arrays of objects:

var a = [{
  "id": 1,
  "name": "q"
},
{
  "id": 2,
  "name": "l"
}]

and another is

var b = [{
  "id": 3,
  "sub": 1,
  "name": "ni"
},
{
  "id": 4,
  "sub": 2,
  "name": "bh"
}]

Here sub is the id in a

I need to have a new array which will look like this:

var c = [
  {
    "id":1,
    "name":"q",
    "map":[
      {
        "id":3,
        "name":"ni"
      }
    ]
  },
  {
    "id":2,
    "name":"l",
    "map":[
      {
        "id":4,
        "name":"bh"
      }
    ]
  }
]

How can I do that in JavaScript?

I am using underscore in my project.

In plain Javascript you could use Array#map , Array#forEach and a hash table.

 var a = [{ "id": 1, "name": "q" }, { "id": 2, "name": "l" }], b = [{ "id": 3, "sub": 1, "name": "ni" }, { "id": 4, "sub": 2, "name": "bh" }], hash = Object.create(null), result = a.map(function (a, i) { hash[a.id] = { id: a.id, name: a.name }; return hash[a.id]; }, hash); b.forEach(function (a) { hash[a.sub].map = hash[a.sub].map || []; hash[a.sub].map.push({ id: a.id, name: a.name }); }, hash); console.log(result); 

ES6

 var a = [{ "id": 1, "name": "q" }, { "id": 2, "name": "l" }], b = [{ "id": 3, "sub": 1, "name": "ni" }, { "id": 4, "sub": 2, "name": "bh" }], hash = Object.create(null), result = a.map((hash => a => hash[a.id] = { id: a.id, name: a.name, map: [] })(hash)); b.forEach((hash => a => hash[a.sub].map.push({ id: a.id, name: a.name }))(hash)); console.log(result); 

You can do it with the help of map function and then use the find function to search the data from the other array.

 var b = [{ "id": 3, "sub": 1, "name": "ni" }, { "id": 4, "sub": 2, "name": "bh" }]; var a = [{ "id": 1, "name": "q" }, { "id": 2, "name": "l" }]; var final = _.map(b, function(d) { return { id: d.name, name: d.name, map: _.find(a, function(adata) { return adata.id == d.sub; //use underscore find to get the relevant data from array a }) } }); console.log(final); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM