skip to Main Content

I want to merge objects with same key into one single object. For example the first array below is the array I am having. I want to convert it into second array

CONVERT BELOW

[
  {
    "speed": 779.5,
    "id": 1
  },
  {
    "code": "04.x.D3",
    "id": 1
  },
  {
    "temperature": 49,
    "id": 1
  },
  {
    "range": 0,
    "id": 1
  },
  {
    "temperature": 41,
    "id": 2
  },
  {
    "range": 3,
    "id": 2
  }
]

INTO THIS

[
  {
    "speed": 779.5,
    "code": "04.x.D3",
    "temperature": 49,
    "range": 0,
    "id": 1
  },
  {
    "temperature": 41,
    "range": 3,
    "id": 2
  }
]

2

Answers


  1. const start = [
      {
        "speed": 779.5,
        "id": 1
      },
      {
        "code": "04.x.D3",
        "id": 1
      },
      {
        "temperature": 49,
        "id": 1
      },
      {
        "range": 0,
        "id": 1
      },
      {
        "temperature": 41,
        "id": 2
      },
      {
        "range": 3,
        "id": 2
      }
    ];
    
    const result = start.reduce(
      (accumulator, value) => {
        // Check if there is already an object in the array with the same id.
        const existing = accumulator.findIndex(({ id }) => value.id === id);
        // If there is an existing object:
        if (existing > -1) {
          // Shallow merge the properties together.
          accumulator[existing] = { ...accumulator[existing], ...value };
          return accumulator;
        }
      
        // Else append this object to the array.
        return accumulator.concat(value);
      },
      // Start with an empty array.
      []
    );
    
    console.log(result);
        
    Login or Signup to reply.
  2. const data = [ { "speed": 779.5, "id": 1 }, { "code": "04.x.D3", "id": 1 }, { "temperature": 49, "id": 1 }, { "range": 0, "id": 1 }, { "temperature": 41, "id": 2 }, { "range": 3, "id": 2 } ];
    
    const result = data.reduce((prev, current) => {
      const index = prev.findIndex(o => o.id === current.id);
      return index < 0 ?
        prev.push(current) && prev :
        prev.splice(index, 1, {...prev[index], ...current}) && prev;
    }, []);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search