Home > database >  How to looping trough an array of object when array name is not consistent?
How to looping trough an array of object when array name is not consistent?

Time:02-08

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.

CodePudding user response:

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);
  });
}

CodePudding user response:

const key = Object.keys(obj).find((key) => key.indexOf('price') > -1)
obj[key].forEach(price => console.log(price))

CodePudding user response:

You can use "Object.values()" or "Object.fromEntries()" to get the values or both keys & values.

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

const priceArray = Object.values(obj).find( value => Array.isArray(value))

FYI

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

  •  Tags:  
  • Related