Home > Software design >  How to filter data of object according to keys and make new array in react?
How to filter data of object according to keys and make new array in react?

Time:12-08

I am working with the object like this:-

{
 0: 
  buyAmount: 16.664328043964396
  buyAmountInUsd: 16.685266204095775
  date: {date: '2021-12-07'}
  sellAmount: {USD: 500, INR: 35000}
 1:
  buyAmount: 1004.7015442959262
  buyAmountInUsd: 1005.9639175379324
  date: {date: '2021-12-07'}
  sellAmount: {USD: 1000, INR: 79000}
......

and I am trying to make a new array using useState hook with this data but the problem I am facing is how to filter data and make an almost similar array with the same data.

e.g.:-

 0: [amount: 500, date: '2021-12-07'], 
 1: [amount: 1000, date: '2021-12-07']

The problem I am facing is I don't know the approach how to get the data like amount = sellAmount.USD and date = date.date

I thought of trying the for...of But I don't think it will be a good hit.

CodePudding user response:

You can do this with Array.map

const arr = [{
  buyAmount: 16.664328043964396,
  buyAmountInUsd: 16.685266204095775,
  date: {date: '2021-12-07'},
  sellAmount: {USD: 500, INR: 35000}
},{
  buyAmount: 1004.7015442959262,
  buyAmountInUsd: 1005.9639175379324,
  date: {date: '2021-12-07'},
  sellAmount: {USD: 1000, INR: 79000}
}]

console.log(
  arr.map(initialValue => {
    return {
      amount: initialValue.sellAmount.USD,
      date: initialValue.date.date
    }
  })
)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The better idea would be the having an array of objects rather than array of array elements

let result = yourArray.map(each => ({ amount: each.sellAmount.USD, date: each.date.date }))

CodePudding user response:

This is not related to ReactJS - just native Javascript object handling.

If your original data has the shape of an Object you can convert it into an Array like so:

const objData = { 0: {...}, 1: {...} };
const arrData = Object.entries(objData); // [[0, {...}], [1, {...}]];

From there, you can filter/map/sort your array with native array methods:

const reshapedArray = arrData.map(([key, value]) => {
  return {
    amount: value.sellAmount.USD,
    date: value.date.date,
  };
});

Then sort:

const sortedArray = reshapedArray.sort((prev, next) => {
  return prev.amount - next.amount; // sort by amount ascending
});

You can of could chain these array functions and shorten the syntax a bit:

Object.entries(objData)
  .map(([_, { sellAmount, date: { date } }]) => ({ amount: sellAmount.USD, date }))
  .sort((a, b) => a.amount - b.amount);
  • Related