skip to Main Content

So I have 3 API sources that return data in this format

firstSource = [{month, endDate, expectedPrice}] ->array of 12 objects
secondSource = [{month, value}] ->array of 12 objects
thirdSource = [{month, value}] ->array of 12 objects

example:

secondSource = [
{month: 1, value: 234.22},
{month: 2, value: 123.58},
{month: 3, value: 255.35},
...
...
you get the idea
]

I’ve come across this solution that uses lodash library. This is all well, but I’m interested in a solution that doesn’t require external libraries. So basically, I want to achieve the same thing the person from the lodash solution did -> combine all three data sources into one and then use that to display the data in <table> element, only without using external libraries, e.g. lodash.

Expected output:

combined = [
{month, endDate, expectedPrice, secondSourceValue, thirdSourceValue}
]

Any ideas?

2

Answers


  1. We can use array.mapto merge multiple arrays of objects and create a new array with properties of all objects.

    Do note that, in this case, the length of all the arrays should be the same.

    let arr1 = [{
        month: 1,
        value: 234.22,
        date: 'JAN'
      },
      {
        month: 2,
        value: 123.58,
        date: 'FEB'
      },
      {
        month: 3,
        value: 255.35,
        date: 'MARCH'
      }
    ]
    
    let arr2 = [{
        month: 1,
        property: 1
      },
      {
        month: 2,
        property: 2
      },
      {
        month: 3,
        property: 3
      }
    ]
    
    let arr3 = [{
        month: 1,
        property: 9
      },
      {
        month: 2,
        property: 8
      },
      {
        month: 3,
        property: 7
      },
    ]
    
    
    let combinedArr = arr1.map((item, index) => {
      return {
        ...item,
        ...arr2[index],
        ...arr3[index]
      }
    })
    
    console.log(combinedArr)
    Login or Signup to reply.
  2. what’s the problem to try something like this?

    let combinedData = []
    
    firstSource.forEach((element, index) => {
        combinedData[index] = {
          month: element.month,
          endDate: element.endDate,
          expectedPrice: element.expectedPrice,
          secondSourceValue: secondSource[index].value,
          thirdSourceValue: thirdSource[index].value
    }    
    });
    

    You only have to check if the second and third sources have the same length with the main.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search