【问题标题】:How can I extract an object from array? [duplicate]如何从数组中提取对象? [复制]
【发布时间】:2019-07-17 19:09:31
【问题描述】:

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

});

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

【问题讨论】:

  • 看来 filter() 会是个不错的选择。
  • 你想要的结果是什么?
  • 使用reduce函数。
  • props对象的格式是否一致?使用组件访问数组是否总是props[0].user.new_functions_id?或者会有多个props,都带有user.new_functions_id,你需要包含all它们?
  • let newtypes 正如我在问题末尾所说的那样。相同的第一个 var 但没有 props 中存在的元素

标签: javascript


【解决方案1】:

您可以将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)

【讨论】:

    【解决方案2】:

    如果您想检查第一个数组中的项目是否在第二个数组中,您可以尝试以下操作:types.filter(a => b.includes(a))

    【讨论】:

      【解决方案3】:

      尝试以下方法: 首先是 map(),然后是 filer()。

      【讨论】:

        猜你喜欢
        • 2020-06-08
        • 1970-01-01
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 2011-09-18
        • 1970-01-01
        • 2023-01-25
        • 2018-06-30
        相关资源
        最近更新 更多