Filter object for a nested array (Javascript)

旧城冷巷雨未停 提交于 2020-07-23 06:23:34

问题


Based on an object like this:

var p = [
           {x: [
                 {x1: "John"}, 
               ]
           },
           {x: [
                 {x1: "Louis"},
               ]
           }
        ];

I need to filter p objects when x1 is different from any of those values:

var p = [
           {x: [
                 {x1: "Louis"}, 
               ]
           },
        ];

Thanks all of you for your help.


回答1:


It is exactly the same as your question with the numbers.

var p = [
           {x: [
                 {x1: 'John'}, 
               ]
           },
           {x: [
                 {x1: 'Louis'},
               ]
           }
        ];

const results = p.filter(val => !val.x.some(v => v.x1 === 'John'));

console.log(results);



回答2:


Use filter method and destructuring. Check for condition in filter method.

var p = [{ x: [{ x1: "John" }] }, { x: [{ x1: "Louis" }] }];

const filter = (arr, item) => arr.filter(({ x: [{ x1 }] }) => x1 !== item);

console.log(filter(p, "John"));
console.log(filter(p, "Louis"));



回答3:


I'm not sure what you mean by filter, but based on my intuition of what you're searching for, you could perhaps use an if statement:

If ((p.x.x1 !== "John") && (p.x.x1 !== "Louis") {
//Your code
};


来源:https://stackoverflow.com/questions/62869085/filter-object-for-a-nested-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!