我有一个像这样的对象数组:
users: [
{ name: 'missing!', ids: ['Not Specified']},
{ name: 'user1', ids: ['C.001', 'C.002', 'C.001.001']},
{ name: 'user2', ids: ['C.001', 'C.002', 'C.004', 'C.001.001']},
{ name: 'user3', ids: ['C.001', 'C.002', 'C.004', 'C.001.001']},
{ name: 'user4', ids: ['C.001', 'C.002', 'C.004', 'C.001.001']}
]
我想要实现的是获取一个具有一定ID的用户名数组。
例如,如果我传递一个ID:'C.001.001',则应返回['user1','user2','user3','user4']。
如果我通过'C.123214123',则应该返回['missing!']。
我尝试过但没有用的东西:
getUserNamesById(id: string) string[] {
return _.map(this.users, user => {
return _.find(user.ids,{id});
});}
这不起作用,也无法处理您找不到ID并返回['missing'](并且也不会返回name属性)的情况。
我是_.lodash的新手,我想学习它,但是我研究了将近2个小时,却一无所获。
我如何实现输出?
答案 0 :(得分:1)
您需要分别处理“遗失”案。
您需要过滤列表以获取匹配的内容
如果有匹配项,请映射以获取名称
否则得到“丢失”记录
const users = [
{ name: 'missing!', ids: ['Not Specified']},
{ name: 'user1', ids: ['C.001', 'C.002', 'C.001.001']},
{ name: 'user2', ids: ['C.001', 'C.002', 'C.004', 'C.001.001']},
{ name: 'user3', ids: ['C.001', 'C.002', 'C.004', 'C.001.001']},
{ name: 'user4', ids: ['C.001', 'C.002', 'C.004', 'C.001.001']}
];
function find(u, search) {
const found = _.filter(u, (x) => _.some(x.ids, (id) => id === search));
if (_.isEmpty(found)) {
return ['missing!'];
} else {
return _.map(found, (f) => f.name);
}
}
console.log(find(users, 'C.001.001'));
console.log(find(users, 'C.123.456'));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
答案 1 :(得分:1)
您可以将"HEADER_ROW1_COL1,WITH_COMMA",HEADER_ROW1_COL2,my darling's ccc
DATA_ROW2_COL1,DATA_ROW2_COL2
DATA_ROW3_COL1,DATA_ROW3_COL2
与Array.filtered()
(或类似的破折号)一起使用,以过滤数组,然后使用Array.includes()
获取名称列表:
Array.map()
与lodash/fp的想法相同:
const filterById = (id, arr) => {
const filtered = arr.filter(({ ids }) => ids.includes(id))
.map(({ name }) => name);
return filtered.length ? filtered : ['missing'];
}
const users = [{"name":"missing!","ids":["Not Specified"]},{"name":"user1","ids":["C.001","C.002","C.001.001"]},{"name":"user2","ids":["C.001","C.002","C.004","C.001.001"]},{"name":"user3","ids":["C.001","C.002","C.004","C.001.001"]},{"name":"user4","ids":["C.001","C.002","C.004","C.001.001"]}]
console.log(filterById('C.001.001', users));
console.log(filterById('132133333', users));
const { flow, filter, get, includes, map, cond, isEmpty, constant, stubtrue, identity } = _
const filterById = id => flow(
filter(flow(get('ids'), includes(id))),
cond([
[isEmpty, constant(['missing'])],
[stubtrue, map('name')]
])
)
const users = [{"name":"missing!","ids":["Not Specified"]},{"name":"user1","ids":["C.001","C.002","C.001.001"]},{"name":"user2","ids":["C.001","C.002","C.004","C.001.001"]},{"name":"user3","ids":["C.001","C.002","C.004","C.001.001"]},{"name":"user4","ids":["C.001","C.002","C.004","C.001.001"]}]
console.log(filterById('C.001.001')(users));
console.log(filterById('132133333')(users));