Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 981
nirvair Avatar asked Jan 23 '26 17:01

nirvair


1 Answers

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);
like image 54
Nina Scholz Avatar answered Jan 26 '26 07:01

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!