【问题标题】:How can I find objects with same keys values in array?如何在数组中找到具有相同键值的对象?
【发布时间】:2022-01-11 14:50:43
【问题描述】:

我有一个如下所示的对象数组:

  const arr = [
    { type: 'type', fields: ['field1'] },
    { type: 'type2' },
    { type: 'type', fields: ['field2'] },
  ]

并且我需要找到具有相同类型的对象来合并其中的字段键,如下所示:

  const arr = [
    { type: 'type', fields: ['field1', 'field2'] },
    { type: 'type2' },
    { type: 'type', fields: ['field1', 'field2'] },
  ]

我的计划是通过数组进行过滤,但我的问题是我不知道哪种类型会向我发送 API,因此按 item.type 过滤对我不起作用。

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

如果那是您想要的确切解决方案。以下代码 sn -p 可能会对您有所帮助。

    const arr = [
      { type: 'type', fields: ['field1']},
      { type: 'type2'},
      { type: 'type', fields: ['field2']}
    ]
    
    const modifyArr = (data) => {
      let res = [];
      arr.map((item) => {
          if(item.type == data.type){
            if(Object.keys(item).includes('fields')){
              res = res.concat(item.fields);
            }
          }
      });
      return Object.keys(data).includes('fields') ? { type: data.type, fields: res } : { type: data.type };

}

let newArr = arr.map(item => modifyArr(item));

console.log(newArr); 

这将打印出来

[
    { type: 'type', fields: ['field1', 'field2'] },
    { type: 'type2' },
    { type: 'type', fields: ['field1', 'field2'] },
  ]

【讨论】:

    【解决方案2】:

    const arr = [{ type: 'type', fields: ['field1']}, { type: 'type2'}, { type: 'type', fields: ['field2']}];
    
    result = arr.map(({ type }) => {
        const fields = arr.filter((o) => o.type === type).flatMap((e) => e.fields);
        return { type, ...fields[0] ? { fields } : {} };
    });
    
    console.log(result);
    //[
    //    {"type": "type", "fields": ["field1", "field2"]},
    //    {"type": "type2"},
    //    {"type": "type", "fields": ["field1", "field2"]}
    //]

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 2022-06-10
      • 2019-11-03
      • 2018-12-07
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多