Home > Enterprise >  Not able to add JSON Data inside forEach loop using if condition on elements
Not able to add JSON Data inside forEach loop using if condition on elements

Time:02-14

Hi I am trying to add few conditional data from one JSON object to another.I am trying below code.Data is having JSON object.I am not getting any one in Data though i am getting correct value in Temp

const userData= data.rows;
    const claimsB = claimsB;
    let Temp = '';
    let Data = '';
    userData.forEach((element) => {
        if (element.value.A == claimsB.B){
            Temp = element;
            Data  = Temp;
        }
        console.log(Temp);
    });
   console.log(Data);

CodePudding user response:

Perhaps you want to replace

Data = Temp;

with

Data = JSON.stringify(Temp);

CodePudding user response:

let Temp = ''; and let Data = ''; specify that both "Temp" and "Data" are declared as empty strings

Temp = element; is assigning the "element" object to "Temp" variable At this point, type of "Temp" is converted to Object

Data = Temp; is trying to append an object to a string. At this point, type of "Data" is still String

As per your statement, you expect "Data" to be a JSON object but that is not the case. Hence, when you try to console.log(Data) at the end of your snippet, you might be seeing [object Object]... instead of a JSON object.

Suggestion: Declare "Data" as an array and push conditionally matching elements to this. Your code will look like this:

const userData= data.rows;
let Data = [];
userData.forEach((element) => {
    if (element.value.A == claimsB.B){
        Data.push(element);
    }
    console.log(Temp);
});
console.log(Data);
  • Related