假设我有以下格式的数据作为json发送
[
{
"clauseId": 1,
"clauseName": "cover",
"texts": [
{
"textId": 1,
"text": "hello"
}
]
},
{
"clauseId": 3,
"clauseName": "xyz",
"texts": [
{
"textId": 3,
"text": "hello Everyone"
},
{
"textId": 4,
"text": "Some data"
}
]
}
{
"clauseId": 2,
"clauseName": "joining",
"texts": [
{
"textId": 3,
"text": "hello1"
},
{
"textId": 4,
"text": "hello2"
}
]
}
]
我已经从子句名称中列出一个列表,例如
c=[joining,xyz]
我想在其中列出文本的位置
d=[hello Everyone,Some data,hello1,hello2]
请提出一些建议
let filters = ['hello Everyone','Some data','hello1','hello2'];
const result = arr.filter(f =>
f.texts.some(s => filters.includes(s.text)))
.map(a => a.clauseName);
const arr = [ { "clauseId": 1, "clauseName": "cover", "texts": [ { "textId": 1, "text": "hello" } ] }, { "clauseId": 3, "clauseName": "xyz", "texts": [ { "textId": 3, "text": "hello Everyone" }, { "textId": 4, "text": "Some data" } ] }, { "clauseId": 2, "clauseName": "joining", "texts": [ { "textId": 3, "text": "hello1" }, { "textId": 4, "text": "hello2" } ] } ] let filters = ['hello Everyone','Some data','hello1','hello2']; const result = arr.filter(f=> f.texts.some(s => filters.includes(s.text))).map(a=>a.clauseName); console.log(result);
UPDATE 1:
如果要按['joining','xyz'];
进行过滤,则可以使用filters
数组并检查includes
方法是否包含数据:
let filters = ['joining','xyz']; const result = arr.filter(f => filters.includes(f.clauseName)) .flatMap(r => r.texts.map(t => t.text)); console.log(result);
const arr = [ { "clauseId": 1, "clauseName": "cover", "texts": [ { "textId": 1, "text": "hello" } ] }, { "clauseId": 3, "clauseName": "xyz", "texts": [ { "textId": 3, "text": "hello Everyone" }, { "textId": 4, "text": "Some data" } ] }, { "clauseId": 2, "clauseName": "joining", "texts": [ { "textId": 3, "text": "hello1" }, { "textId": 4, "text": "hello2" } ] } ] let filters = ['joining','xyz']; const result = arr.filter(f => filters.includes(f.clauseName)) .sort((a,b) => a.clauseId - b.clauseId) .flatMap(r => r.texts.map(t => t.text)); console.log(result);
result = [];
constructor() {
let texts:any[] = this.data.filter(item => this.c.includes(item.clauseName)).sort((a, b) => a.clauseId - b.clauseId).flatMap(x => x.texts);
this.result = texts.map(x => x.text);
}