将键值映射到数据中的其他值

问题描述 投票:1回答:2

假设我有以下格式的数据作为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]

请提出一些建议

angular typescript list dictionary collections
2个回答
0
投票
您可以过滤,然后获取所需的字段:

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);

0
投票
尝试这样:

Working Demo

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); }
© www.soinside.com 2019 - 2024. All rights reserved.