[英]How to loop list of array in another response of array of object using *ngfor?
let say I have two responses.假设我有两个回应。 one response consist of array, let temp1 =
[name, description, address]
;一个响应由数组组成,让 temp1 =
[name, description, address]
;
second response consist of array of objects, let temp2 =第二个响应由对象数组组成,让 temp2 =
[
{
name: "name1",
description: "not a current user",
address: "address 1",
phoneno: 123,
check1: true,
pined: "no",
user: "yes"
},
{
name: "name2",
description: "current user",
address: "address 2",
phoneno: 1234,
check1: false,
pined: "no",
user: "yes"
},
{
name: "name3",
description: "current user",
address: "address 3",
phoneno: 12345,
check1: false,
pined: "no",
user: "yes"
}
]
<table>
<thead>
<tr>
<th *ngFor="let temp of temp1">{{temp}}</th>
</tr>
</thead>
<tbody>
<tr><td *ngFor="let body of temp2; let i = index">{{body.temp[i]}}</td></tr>
</tbody>
</table>
I want to loop tbody only with list of array available in temp 1, not with all the list in temp2 it should be dynamic.我只想用 temp 1 中可用的数组列表循环 tbody,而不是 temp2 中的所有列表,它应该是动态的。 whatever its in temp1 only that values should be loop in tbody.
无论它在 temp1 中,只有值应该在 tbody 中循环。
Thanks in advance, I'm using angular 11 in my project在此先感谢,我在我的项目中使用 angular 11
It's easily solved with a classic JavaScript class getter.使用经典的 JavaScript 类 getter 很容易解决这个问题。 Getters are method defined with the get keyword that are visible as properties.
Getter 是使用get关键字定义的方法,它们作为属性可见。 Let's say you have something like this:
假设你有这样的事情:
class Cl {
constructor() {
this.data = [1, 2, 3, 4, 5];
}
get dt() {
return this.data.filter(n => n < 4);
}
}
const cl = new Cl();
console.log(cl.dt);
The console will output [1, 2, 3].控制台将输出 [1, 2, 3]。 Now that we have made this clear, let's find an answer to your question:
既然我们已经说清楚了,让我们来回答您的问题:
get dt() {
const ret = [];
for (const elem of this.temp2) {
ret.push(
this.temp1.reduce((obj, k) => Object.assign(obj, {[k]: elem[k]}), {})
);
}
return ret;
}
Let's dig into the code:让我们深入研究代码:
Obviously, you'll have to use the *ngFor against the dt getter.显然,您必须对 dt getter 使用 *ngFor。
Hope this solve your problem (: Happy coding!希望这能解决您的问题(:快乐编码!
EDIT Even better using the array's map method编辑使用数组的map方法更好
get dt() {
return this.temp2.map(elem => this.temp1.reduce((obj, k) => Object.assign(obj, {[k]: elem[k]}), {}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.