在Angular中,可以使用Array.prototype.find()
方法来获取另一个数组中的JSON数组。以下是一个示例代码:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Result:
{{ result | json }}
`,
})
export class ExampleComponent implements OnInit {
// 另一个数组
anotherArray = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' },
];
// JSON数组
jsonArr = [
{ id: 1, data: 'Data 1' },
{ id: 2, data: 'Data 2' },
{ id: 3, data: 'Data 3' },
];
result: any;
ngOnInit() {
this.result = this.jsonArr.map(json => {
const obj = this.anotherArray.find(another => another.id === json.id);
return { ...json, name: obj ? obj.name : 'Unknown' };
});
}
}
在上面的示例中,我们使用Array.prototype.map()
方法遍历jsonArr
数组,并使用Array.prototype.find()
方法在anotherArray
中查找与当前元素的id匹配的对象。如果找到匹配的对象,则将其名称添加到当前JSON对象中,否则将名称设置为'Unknown'。最后,将结果存储在result
变量中,并在模板中显示。
请注意,以上示例假设id
属性在两个数组中是唯一的,并且anotherArray
中的每个对象都有一个与之对应的JSON对象。如果这些条件不满足,代码可能需要进行适当的修改。