Home > front end >  How to transform each key in my object that has array data to an object that separate to the size of
How to transform each key in my object that has array data to an object that separate to the size of

Time:05-20

Pretend that i have this output data:

const fixedObj = {
 factory: 'QWERTY',
}
const flexibleObj = {
 itemName: ['abc', 'xyz'],
 quantity: ['1', '2'],
 color: ['red', 'blue'],
 price: ['20$', '30$'],
}

These 2 objects are from one big object but they have to be separated for knowing if the key has array or not. If the key holds the data which has array like flexibleObj then the final output should be like this:

{
 factory: 'QWERTY',
 itemName: 'abc',
 quantity: '1',
 color: 'red',
 price: '20$'
},
{
 factory: 'QWERTY',
 itemName: 'xyz',
 quantity: '2',
 color: 'blue',
 price: '30$'
}

My question is: is there any posible way to convert like this ?

CodePudding user response:

You can iterate over the itemName array and use the current index to get the information from all the other arrays to build a new object.

const fixedObj={factory:"QWERTY"},flexibleObj={itemName:["abc","xyz"],quantity:["1","2"],color:["red","blue"],price:["20$","30$"]};

// Destructure the properties from the object
const {
  itemName,
  quantity,
  color,
  price
} = flexibleObj;


// Iterate over the itemName array and utilise
// the index to get the elements of the other
// arrays to build an object
const arr = itemName.map((item, i) => {
  return {
    factory: fixedObj.factory,
    itemName: item,
    quantity: quantity[i],
    color: color[i],
    price: price[i]
  };
});

console.log(arr);

CodePudding user response:

const fixedObj = {
  factory: 'QWERTY',
}

const flexibleObj = {
  itemName: ['abc', 'xyz'],
  quantity: ['1', '2'],
  color: ['red', 'blue'],
  price: ['20$', '30$'],
}

const result = []
for (let i = 0; i < flexibleObj.itemName.length; i  ) {
  result.push({
    ...fixedObj,
    itemName: flexibleObj.itemName[i],
    quantity: flexibleObj.quantity[i],
    color: flexibleObj.color[i],
    price: flexibleObj.price[i],
  })
}


console.log(result)

CodePudding user response:

Here is a generic approach that takes care of all existing properties in flexibleObj and fixedObj:

const fixedObj={factory:"QWERTY", location:"Hanover"},flexibleObj={itemName:["abc","xyz"],quantity:["1","2"],color:["red","blue"],price:["20$","30$"],extra:[7,13]};

const flex=Object.entries(flexibleObj);
const arr = flex[0].map((_,i)=>{
  const o = {...fixedObj};
  flex.forEach(([k,ar])=>o[k]=ar[i]);
  return o;
});

console.log(arr);

  • Related