将对象数组中两个属性的唯一值存储到单个数组中

时间:2019-05-22 05:19:12

标签: javascript arrays ecmascript-6 set javascript-objects

如何获取requesterPractitionerId和performerOrganizationId的唯一值。我需要在单个数组中探索requesterPractitionerId和performerOrganizationId的唯一值。

[ 
    { 
        id: '1043120',
        requesterPractitionerId: '1043119',
    },
    { 
        id: '1043081',
        requesterPractitionerId: '1043080'
    },
    { 
        id: 'e1dceebe-c5ba-46a5-a63a-bff709896af4',
        requesterPractitionerId: 'e0a844e4-6c8a-489a-8bd6-1d62267d311e',
        performerOrganizationId: '05D0889009',
    },
    { 
        id: '2709842f-41e3-4193-8607-fc34d3d24ec1',
        requesterPractitionerId: 'e0a844e4-6c8a-489a-8bd6-1d62267d311e',
        performerOrganizationId: '05D0889009'
    } 
]

预期输出:

1043119
1043080
e0a844e4-6c8a-489a-8bd6-1d62267d311e
05D0889009

我是Java语言的新手,并为此奋斗了两个小时。任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

一种解决方案是使用Array.reduce()从所需的属性中生成新的Set。之后,您可以spread将集合中的项目放入数组中。

const input = [{id:'1043120',requesterPractitionerId:'1043119'},{id:'1043081',requesterPractitionerId:'1043080'},{id:'e1dceebe-c5ba-46a5-a63a-bff709896af4',requesterPractitionerId:'e0a844e4-6c8a-489a-8bd6-1d62267d311e',performerOrganizationId:'05D0889009',},{id:'2709842f-41e3-4193-8607-fc34d3d24ec1',requesterPractitionerId:'e0a844e4-6c8a-489a-8bd6-1d62267d311e',performerOrganizationId:'05D0889009'}];

let res = input.reduce((acc, o) =>
{
    if (o.hasOwnProperty("requesterPractitionerId"))
        acc.add(o.requesterPractitionerId);

    if (o.hasOwnProperty("performerOrganizationId"))
        acc.add(o.performerOrganizationId);

    return acc;
}, new Set())

console.log([...res]);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 1 :(得分:0)

非常简单-Setmapreducefilter

const arr = [{id:'1043120',requesterPractitionerId:'1043119',},{id:'1043081',requesterPractitionerId:'1043080'},{id:'e1dceebe-c5ba-46a5-a63a-bff709896af4',requesterPractitionerId:'e0a844e4-6c8a-489a-8bd6-1d62267d311e',performerOrganizationId:'05D0889009',},{id:'2709842f-41e3-4193-8607-fc34d3d24ec1',requesterPractitionerId:'e0a844e4-6c8a-489a-8bd6-1d62267d311e',performerOrganizationId:'05D0889009'}];
const res = [...new Set(arr.map(({ requesterPractitionerId, performerOrganizationId }) => [requesterPractitionerId, performerOrganizationId]).reduce((acc, curr) => acc.concat(curr)).filter(Boolean))];
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }