Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Im using react Js, I have a list of Objects, the first object has a elements of array same thing with second Object

i have a List of objects here

const List_objects = [
 { 
   Product = A,
   Price = 20
 },
 {
   Product = B,
   Price = 21
 }
]

and I have a person_data with

const [person_data,setPerson_Data] = useState({
  Product : 0,
  Price = :0
})

and i have a onClick function here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const handleClick = e => {
  setPerson_Data({
      Product: String(List_objects.map(e=>e.Product)),
      Price : String(List_objects.map(e=>e.Price))
   })

and when I print via console.log this will be the result

 {
    Product: A,B,
    Price : 20,21
  }

and I wanted to do it in reverse

from these

{
   Product: A,B,
   Price : 20,21
}

into these

[
  { 
    Product = A,
    Price = 20
  },
  {
    Product = B,
    Price = 21
  }
]

I am 3rd yr ComEng student and i am developing a Online Inventory System using React JS it will really a great help in my school specially my career as aspirant developer

do you guys any idea how to execute it ? or maybe some alternative also it will help if there is sample code

THANK YOU IN ADVANCE!

>Solution :

Here are two possible ways go create the array from it. One uses a Generator, the other uses map().

const input = {
  Product: "A,B",
  Price: "20,21",
};

function* fromObjectGenerator(obj) {
  const products = obj.Product.split(",");
  const prices = obj.Price.split(",");
  for (let i = 0; i < products.length; i++) {
    yield {
      Product: products[i],
      Price: prices[i],
    };
  }
}

function fromObject(obj) {
  const products = obj.Product.split(",");
  const prices = obj.Price.split(",");
  return [...Array(products.length)].map((_, idx) => ({
    Product: products[idx],
    Price: prices[idx],
  }));
}

console.log([...fromObjectGenerator(input)]);
console.log(fromObject(input));

Please note: Both implementations assume that the number of products matches the number of prices but which little adjustments it could also work if that was not the case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading