4 回答
TA贡献1865条经验 获得超7个赞
您可以从 list1 中收集想要的评论,并通过检查其他列表中是否存在某个项目list2的值来减少。elec然后返回一个新对象。
这种方法只需要两个循环。
const
list1 = [{ id: '1', status: 'use', comment: 'xxxx' }, { id: '2', status: 'ready', comment: 'yyyy' }, { id: '3', status: 'ready', comment: 'zzzz' }],
list2 = [{ uid: '1', elec: 60 }, { uid: '2', elec: 60 }, { uid: '10', elec: 60 }, { uid: '3', elec: 40 }],
l1 = list1.reduce((r, { id, status, comment }) => {
if (status === 'ready') r[id] = { comment };
return r;
}, {}),
result = list2.reduce((r, o) => {
if (o.elec > 50 && o.uid in l1) r.push({ ...o, ...l1[o.uid]})
return r;
}, []);
console.log(result);
TA贡献1859条经验 获得超6个赞
let result = {
...list2.filter(
a => a.elec > 50 && a.uid === list1.filter(b => b.status === "ready")[0].id)[0],
comments: list1.filter(b => b.status === "ready")[0].comment
}
TA贡献1839条经验 获得超15个赞
you can restructure your data. List1 convert it in object. And now we can find solution in O(n).
let list1 = [{
id: '1',
status: 'use',
comment: 'xxxx'
}, {
id: '2',
status: 'ready',
comment: 'yyyy'
}, {
id: '3',
status: 'ready',
comment: 'zzzz'
}];
let list2 = [{
uid: '1',
elec: 60
}, {
uid: '2',
elec: 60
}, {
uid: '10',
elec: 60
}, {
uid: '3',
elec: 40
}];
const itemList = {}
list1.forEach(item => {
if (item.status === 'ready') {
itemList[item.id] = item.comment
}
});
const result = list2.filter(item => itemList[item.uid] && item.elec > 50).map(item => {
item['comment'] = itemList[item.uid]
return item
})
console.log(result)
TA贡献1824条经验 获得超6个赞
尝试这个:
let list1 = [
{ id: '1', status: 'use', comment: 'xxxx' },
{ id: '2', status: 'ready', comment: 'yyyy' },
{ id: '3', status: 'ready', comment: 'zzzz' },
];
let list2 = [
{ uid: '1', elec: 60 },
{ uid: '2', elec: 60 },
{ uid: '10', elec: 60 },
{ uid: '3', elec: 40 },
];
let result = null;
let itemFound;
const filteredList = list2.filter((list2Item) => {
if (!result) {
itemFound =
list2Item.elec > 50 &&
list1.find(
(list1Item) =>
list2Item.uid === list1Item.id && list1Item.status === 'ready'
);
if (itemFound) {
result = {
uid: list2Item.uid,
elect: list2Item.elec,
comment: itemFound.comment,
};
}
}
});
console.log(result);
添加回答
举报