Home > Mobile >  How can I find objects with same keys values in array?
How can I find objects with same keys values in array?

Time:12-07

I have an array of objects that looks like this:

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

And I need to find objects with the same type to merge fields key in them, like this:

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

My plan was to filter through the array, but my problem is that I don't know which type will send me API, so filtering by item.type wouldn't work for me.

CodePudding user response:

If that is the exact solution that you want. Following code snippet may help you.

    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); 

This will print

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