How to looping trough an array of object when array name is not consistent? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to looping trough an array of object when array name is not consistent? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Consider below example:

const obj ={
price:[{multiple items},{multiple items}],
name:"",
id:"",
}

i want to apply foreach on price property but the issue is the property name is changing wrt cases like saleprice , taxprice etc.

if i am using obj.keys() method it doesn’t work because it returns key as a string.

Answer

You can try this:

const obj = {
  price: [10, 20, 30],
  name: "",
  id: "",
};

const pricePropertyName = Object.keys(obj).find((prop) => prop.includes('price'));
if (pricePropertyName) {
  obj[pricePropertyName].forEach(el => {
    console.log(el);
  });
}
We are here to answer your question about How to looping trough an array of object when array name is not consistent? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji