javascriptfor-loopfor-of-loop

How can I retrieve data from two different const and put it in a for


This is my code:

const data1 = [{ data2:...,data3....}]
const data4 = [{ data5:...,data6:....}]
for (let data2 of data1) {
}

I want to retrieve both date2 of date1 and date5 of date 4

Edit: I solved with "for (let data of [data1,data4])" But now I have another problem, I need to take the value present in all const (in this case it is an ID: 1 field) and pass it to a function, but it returns it to me as undefined. const are structured like this:

const data1 = [{data2: ..., data3 ...., ID = 1}]
const data4 = [{data5: ..., data6: .... ID = 2}]

getdata (data.ID) .done (function () {
});

with one const it works with multiple const me gives them undefined sorry if i'm unclear but i'm still learning.


Solution

  • 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)