js 这样筛选对象数据,怎么比较好

2019-07-19 15:30:57 +08:00
 selfcreditgiving

请问大佬有什么比较简洁一点的写法吗?

const cmds = [
    {name:"a", cmd:"111"},
    {name:"b", cmd:"222"},
    {name:"c", cmd:"333"},
    {name:"d", cmd:"444"},
];

const needExecs = [
    {startCmd:"a", endCmd:"b"},
    {startCmd:"d", endCmd:"d"},
]

// 希望得到过滤后的结果
[
    {name:"a", cmd:"111"},
    {name:"b", cmd:"222"},
    {name:"d", cmd:"444"},
]
2009 次点击
所在节点    问与答
6 条回复
finalwave
2019-07-19 16:36:13 +08:00
如果 cmds 和 needExecs 有序,就
https://gist.github.com/Velocita/695f0631d094457230f8282a208318e2
如果无序就两层循环暴力遍历看要不要 push 进 result
finalwave
2019-07-19 16:38:20 +08:00
不翻墙载入不了链接。。。
重发一下代码
while (i<needExecs.length && j<cmds.length){
if (needExecs[i] include cmds[j].name){
result.push(cmds[j]);
}else if (cmds[j].name left needExecs[i]){
j++;
}else{
i++;
}
}
selfcreditgiving
2019-07-19 16:50:40 +08:00
谢谢大佬回复 :)
这两个数组的 name 属性不是有序的, 可以为任意字符串的。

写了个暴力循环版的,先取到 startCmd 和 endCmd 在 cmds 数组里对应的 index,然后在分别过滤。
```
const filteredCmds = cmds.filter((item, index) => {
let hit = false;
for (let i = 0; i < needExecs.length; i++) {
const startIndex = cmds.findIndex(cmd => cmd.name === needExecs[i].startCmd);
const endIndex = cmds.findIndex(cmd => cmd.name === needExecs[i].endCmd);
if (index >= startIndex && index <= endIndex) {
hit = true;
break;
}
}
return hit;
});
```
johnnyNg
2019-07-19 17:09:46 +08:00
cmds.filter(({name}) => needExecs.find(({startCmd, endCmd}) => startCmd === name || endCmd === name))
selfcreditgiving
2019-07-19 18:12:41 +08:00
@johnnyNg 666, 可以用对象解构。只是意思有点点出入,startCmd、endCmd 的意思是 cmds 数组中,name 值以哪个开始,以哪个结束,

例如:如果 startCmd: "a", endCmd: "c",那么过滤出来的结果应该是
[
{name: "a", cmd: "111"},
{name: "b", cmd: "222"},
{name: "c", cmd: "333"},
]
autoxbc
2019-07-20 01:45:56 +08:00
如果 name 就是单个字母,那么可以考虑拼接正则

const mapFn = ({ startCmd , endCmd }) => startCmd + '-' + endCmd ;
const regExp = new RegExp(`^[${ needExecs.map(mapFn).join('') }]$`);
console.log( cmds.filter( ({ name }) => regExp.test(name) ) );

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/584439

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX