3

I need to parse an API to my application, to get this array of objects:

parsedPlan = [{
id: "start"
small_degressive_rate: 0.22
small_hourly_rate: 2
large_degressive_rate: 0.27
large_hourly_rate: 4.2
},
{
id: "bonus"
small_degressive_rate: 0.21
small_hourly_rate: 1.75
large_degressive_rate: 0.26
large_hourly_rate: 3.55
},
...
]

I tried to filter api data to get the values needed, and then push to a new array: parsedPlan.

import axios from 'axios';

export function parsedPlan() {
  const api = '##########';

  const element = {}; 
  const parsedPlan = [];

  element.id = '';
  element.small_hourly_rate = '';
  element.small_degressive_rate = '';
  element.large_hourly_rate = '';
  element.large_degressive_rate = '';


  axios.get(`${api}/car_prices`)
    .then((response) => {
      const smallPlan = response.data.filter(plan => plan.size == 'S');
      smallPlan.map((plans) => {
        parsedPlan.push({
          id: plans.plan,
          small_hourly_rate: plans.hourly_rate,
          small_degressive_rate: plans.distance_degressive_rate,
        });
      });
      const largePlan = response.data.filter(plan => plan.size == 'XL');
      largePlan.map((plans) => {
        parsedPlan.push({
          id: plans.plan,
          large_hourly_rate: plans.hourly_rate,
          large_degressive_rate: plans.distance_degressive_rate,
        });
      });
    })
    .catch((error) => {
      console.log(error);
    });

  return parsedPlan;
}

For now my parsedPlan looks like this:

parsedPlan = [{
id: "start"
small_degressive_rate: 0.22
small_hourly_rate: 2
},
{
id: "bonus"
small_degressive_rate: 0.21
small_hourly_rate: 1.75
},
...
{
id: "start"
large_degressive_rate: 0.27
large_hourly_rate: 4.2
},
{
id: "bonus"
large_degressive_rate: 0.26
large_hourly_rate: 3.55
},
...
]

And I would like to merge objects with same id. Any ideas how I can get the expected result ?

4
  • Please also put expected Result which you want to achieve which will help a lot to help you. Commented Feb 14, 2019 at 10:59
  • You need to check if an array item with that particular id exists already - and if so, not push the current set of data as a new element, but add the new properties to the already existing one. If you don’t want to have to loop through all already existing entries each time for that check, then I would use an object first, so that you can use the id as property name - then a simple if(object[id]) statement can help you determine whether such an element already exists, or a new one needs to be created. Afterwards, you iterate over all those object properties, and insert them into an array. Commented Feb 14, 2019 at 10:59
  • @Pedro you want to add the values of the objects with same id? Give your expected output please Commented Feb 14, 2019 at 11:11
  • Thank you very much for your answers. A talented friend helped me with this. Working solution: const parsed = parsedPlan.reduce((result, item) => ({ ...result, [item.id]:{ ...(result[item.id] || {}), ...item, }, }), {}) Commented Feb 14, 2019 at 13:45

2 Answers 2

1

You can use the reduce function and in the accumulator array check if there exist an object whose id matches.

If it matches then in that index add a new object which will contain all the keys

let data = [{
    id: "start",
    small_degressive_rate: 0.22,
    small_hourly_rate: 2
  },
  {
    id: "bonus",
    small_degressive_rate: 0.21,
    small_hourly_rate: 1.75
  }, {
    id: "start",
    large_degressive_rate: 0.27,
    large_hourly_rate: 4.2
  },
  {
    id: "bonus",
    large_degressive_rate: 0.26,
    large_hourly_rate: 3.55
  }
]



let newData = data.reduce(function(acc, curr) {
  let findIndex = acc.findIndex(function(item) {
    return item.id === curr.id
  })

  if (findIndex === -1) {
    acc.push(curr)
  } else {
    acc[findIndex] = (Object.assign({}, acc[findIndex], curr))

  }


  return acc;
}, [])


console.log(newData)

Sign up to request clarification or add additional context in comments.

Comments

1

"use reduce function. Create a Object with id as key. Check if id exists or not, if not then create key with name of id else spread the rest values in the existing object and later use Object.Values() to exclude the keys"

const input = [
    {
        id: "start",
        small_degressive_rate: 0.22,
        small_hourly_rate: 2
    },
    {
        id: "bonus",
        small_degressive_rate: 0.21,
        small_hourly_rate: 1.75
    },
    {
        id: "start",
        large_degressive_rate: 0.27,
        large_hourly_rate: 4.2
    },
    {
        id: "bonus",
        large_degressive_rate: 0.26,
        large_hourly_rate: 3.55
    },
];

const output = Object.values(input.reduce((accu, {id, ...rest}) => {
    if(!accu[id]) accu[id] = {};
    accu[id] = {id, ...accu[id], ...rest};
    return accu;
}, {}));

console.log(output);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.