簡體   English   中英

如何在數組中找到具有相同鍵值的對象?

[英]How can I find objects with same keys values in array?

我有一個看起來像這樣的對象數組:

  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過濾對我不起作用。

如果那是您想要的確切解決方案。 以下代碼段可能會對您有所幫助。

    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'] },
  ]

 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"]} //]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM