[英]Combine 2 different javascript json objects into one with a loop and joining on the questionid ,
So I am trying to combine 2 different javascript object than I can end up using in an angularjs ng-repeat . 所以我试图结合2种不同的javascript对象,而最终我无法在angularjs ng-repeat中使用。 since there is a 1 to many relationship from the database, I was pulling queries separately.
由于数据库中存在一对多关系,因此我分别提取查询。
What I have is this: 我所拥有的是:
Main list of data , 3 object sample
0: Object
$$hashKey: "object:4"
Active:true
QuestionId:2
SalesChannel:"DTD"
1: Object
$$hashKey: "object:5"
Active:true
QuestionId:3
SalesChannel:"DTD"
2: Object
$$hashKey: "object:6"
Active:true
QuestionId:5
SalesChannel:"DTD"
Then another query returned data into what I want to relate as JSON into the other object 然后另一个查询将数据返回到我想作为JSON关联到另一个对象的数据
Object { Id: 3, Name: "Text box" QuestionId: 3}
{ Id: 4, Name: "Text box" QuestionId: 3}
{ Id: 9, Name: "Text box" QuestionId: 5}
So since I have both of these objects , I am wanting to combine. 因此,由于我同时拥有这两个对象,因此我想将它们结合起来。
Naturally I would think that I should return from the database, but then I also think about looping over and appending 自然地,我认为我应该从数据库中返回,但是随后我还考虑了循环和追加
for loop on main
{
.... find where main.QuestionId = sub.QuestionId and it to be added in as a nested object of json type...
Thus the end result SHOULD look like 因此最终结果应该看起来像
[{
Active:true,
QuestionId: 3
SubData: [ {
Id: 3,
Name: "TextBox
QuestionId:3
},
{
Id: 4,
Name: "TextBox
QuestionId:3
}],
SalesChannel: "DTD"
}]
// and so on
How can i achieve this? 我怎样才能做到这一点?
You want to go through all of the main objects, and assign to them only those results from second query. 您想要遍历所有主要对象,并仅将第二次查询的结果分配给它们。 Use
Array.prototype.forEach
to go through them all, and Array.prototype.filter
to select only appropriate results from secondary query. 使用
Array.prototype.forEach
遍历所有内容,并使用Array.prototype.filter
从辅助查询中仅选择适当的结果。
firstQueryResult.forEach((firstObject)=>
firstObject.subdata = secondQueryResult.filter((secondObject)=>
secondObject.QuestionId === firstObject.QuestionId))
BTW, this has nothing to do with angularjs 顺便说一句,这与angularjs无关
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects /阵列/的forEach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.