Home > Enterprise >  How to filter and transform object into two level object
How to filter and transform object into two level object

Time:06-18

I'm struggling with this problem. I have this object below.

 const originalData = {
  "price1": 100,
  "amount1": 17.46, 
  "price2": 500,
  "amount2": 29,
  "price3": 700,
  "amount3": 40.74
}

I want a new object inside an array like this below.

const newData =[
  {price:100, amount:17.46},
  {price:500, amount:29},
  {price:700, amount:40.74}      
],

I've tried these methods - filter/map/reduce and googled problom for ages to reach to the result that I wanted. but couldn't get it. please tell me how I can solve this problem.

CodePudding user response:

Assuming the numbers for the keys are consecutive, you can divide the amount of keys by 2 to get the number of objects and create the array using Array#map or Array.from with the keys of the same number.

const originalData = {
  "price1": 100,
  "amount1": 17.46,
  "price2": 500,
  "amount2": 29,
  "price3": 700,
  "amount3": 40.74
}
let res = [...Array(Object.keys(originalData).length/2)]
            .map((_,i)=>({price: originalData[`price${i 1}`], 
                amount: originalData[`amount${i 1}`]}));
console.log(res);

CodePudding user response:

You can simply achieve it by using this logic :

const originalData = {
  "price1": 100,
  "amount1": 17.46, 
  "price2": 500,
  "amount2": 29,
  "price3": 700,
  "amount3": 40.74
};

const arr = [];

Object.keys(originalData).forEach((key, index) => {
  if (originalData[`price${index 1}`]) {
    const obj = {};
    obj.price = originalData[`price${index 1}`]
    obj.amount = originalData[`amount${index 1}`]
    arr.push(obj);
  }
});

console.log(arr);

  • Related