You can create a method getObjByKey
to find in the provided arr
array the object that contains key
property and use Destructuring assignment the get the value
Code:
const getObjByKey = (key, arr) =>
arr.find((obj) => Object.entries(obj).find(([k, v]) => key === k));
Then you can do:
const { data2 } = getObjByKey('data2', date1);
const { date5 } = getObjByKey('date5', date4);
Code example:
// date1 example based on the question code
const date1 = [{ data1: []}, { data2: [1, 2, 3, 4]}]
const getObjByKey = (key, arr) =>
arr.find((obj) => Object.entries(obj).find(([k, v]) => key === k))
const { data2 } = getObjByKey('data2', date1)
// Now you do your logic with `data2`
console.log(data2)
4
solved How can I retrieve data from two different const and put it in a for [closed]