我需要从对象数组(“类型”)中删除一些对象,并创建另一个名为“ newtypes”的数组
let types = [
{value:"a", label:"xxx", component: "Demographic"},
{value:"b", label:"xxx", component: "Elastic"},
{value:"c", label:"xxx", component: "Another"},
{value:"d", label:"xxx", component: "Another2"},
];
let props = [{user : {new_functions_id: [
{component: "Demographic", function_count: 4, new_functions_id: 2},
{component: "Elastic", function_count: 2, new_functions_id: 1},
]}}
];
console.log(types);
console.log(props);
/*
I have to create this var:
let newtypes = [
{value:"a", label:"xxx", component: "Demographic"},
{value:"b", label:"xxx", component: "Elastic"},
];
*/
我正在尝试使用以下方法循环数组:
newtypes = types.map( a => {
if(a.component == b.component)
});
但是我一直在思考如何比较或检查第二个数组的值是否在第一个数组中。
答案 0 :(得分:3)
您可以结合使用filter
和find
仅获得具有匹配组件的项目:
let types = [
{value:"a", label:"xxx", component: "Demographic"},
{value:"b", label:"xxx", component: "Elastic"},
{value:"c", label:"xxx", component: "Another"},
{value:"d", label:"xxx", component: "Another2"},
];
let props = [{user : {new_functions_id: [
{component: "Demographic", function_count: 4, new_functions_id: 2},
{component: "Elastic", function_count: 2, new_functions_id: 1},
]}}
];
const newTypes = types.filter(type =>
props[0].user.new_functions_id.find(id => id.component === type.component)
)
console.log(newTypes)
答案 1 :(得分:1)
如果要检查第一个数组中的项是否在第二个数组中,可以尝试以下操作:types.filter(a => b.includes(a))
答案 2 :(得分:0)
请尝试以下操作: 首先是map(),然后是filer()。