Home > Blockchain >  Method to filter this object
Method to filter this object

Time:11-29

I receive a axios api response in following manner,

  res.data = { 
        material:['plate','bag','bottle'], 
        customer:['cust1','cust2','cust3'], 
        prod_id: [1122,3344,4445]
        }

now I want to rearrange this object to the display data in the table in below manner,

 rowdata = [
        {
            materail:'plate',
            customer:'cust1',
            prod_id:'1122',
        },
        {
            materail:'bag',
            customer:'cust2',
            prod_id:'3344',
        },
        {
            materail:'bottle',
            customer:'cust3',
            prod_id:'4445',
        },
       ]

I am noob at javascript, many things still new to me, your opinions and help will be useful.

I tried object.entries(), foreach() and map() but I cannot achieve the rowdata format.

CodePudding user response:

The easiest way would probably to map one of the list and use the index to access the other ones. Something like this:

const rowdata = res_data.material.map((material, index) => ({
    material,
    customer: res_data.customer[index],
    prod_id: res_data.prod_id[index],
});

CodePudding user response:

You can use the index as you are iterating to grab the values from the other arrays.

const rowData = res.data.prod_id.map((prod_id, i) => {
  const material = res.data.material[i];
  const customer = res.data.customer[i];
  return {
    prod_id,
    material,
    customer,
  };
});

CodePudding user response:

Here is my code using Object.keys() method to iterate the data, and then use reduce() function to map as result.

const raw = Object.keys(data).reduce((pre, current) => {
    return data[current].map((value, index) => ({
        [current]: value,
        ...pre[index],
    }));
}, []);

CodePudding user response:

I agree with the approach of @Ha Tai and @Nina Scholz, but destructuring in each loop is expensive.
Here is my proposition without destructuring:

  const properties=Object.keys(data)
  const result = data[properties[0]].map((elem, i) => {
    return properties.reduce((acc, curr) => {
        acc[curr] = data[curr][i]
      return acc
    }, {})
  })

CodePudding user response:

An data agnostic approach

You could transpose and map new objects. This works for any depth as long as the length is the same and for count of keys.

const
    data = { material: ['plate', 'bag', 'bottle'], customer: ['cust1', 'cust2', 'cust3'], prod_id: [1122, 3344, 4445] },
    result = Object
        .entries(data)
        .reduce(
            (r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })),
            []
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related