[英]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
下面子是id在
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? 如何在JavaScript中做到这一点?
I am using underscore in my project. 我在项目中使用下划线。
In plain Javascript you could use Array#map
, Array#forEach
and a hash table. 在纯Javascript中,您可以使用
Array#map
, Array#forEach
和哈希表。
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 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. 您可以借助
map
函数来执行此操作,然后使用find
函数从另一个数组中搜索数据。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.