如何从数组中提取对象?

时间:2019-07-17 19:09:31

标签: javascript

我需要从对象数组(“类型”)中删除一些对象,并创建另一个名为“ 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)

});

但是我一直在思考如何比较或检查第二个数组的值是否在第一个数组中。

3 个答案:

答案 0 :(得分:3)

您可以结合使用filterfind仅获得具有匹配组件的项目:

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()。