0

I have a question regarding iteration in the js file of an lwc component

I have a array of the following JSON format

[{"key":"0036F00003hXBGAQA4","value":"0016F00003a1iEkQAI"}, {"key":"0036F00003hXBGAQE4","value":"0016F00003a1iEkQAG"}]

Now, is there any way to directly get the value from this array using the key?

I realize that I can iterate through the array, but I don't want to do that because there is already an existing loop and if I have to iterate through this, that will result in an inner loop , which is not the best practice.

I would like to understand if there is some way to get the value, like we do for apex, using the get() method. If this is not possible is there any possibility of creating a map from the above JSON and then use that to fetch the value?

2

I realize that I can iterate through the array, but I don't want to do that because there is already an existing loop and if I have to iterate through this, that will result in an inner loop , which is not the best practice.

Inner loops are not good, but it depends on some situations. So the above statement is not always correct.

Anyways, you need to iterate once to to atleast create a Map with a Key Value pair if the key will be unique in your array. NOTE: Assuming your key is always unique. Orelse you might need to have a Map with values as array.

    const jsonValues = JSON.parse('[{"key":"0036F00003hXBGAQA4","value":"0016F00003a1iEkQAI"}, {"key":"0036F00003hXBGAQE4","value":"0016F00003a1iEkQAG"}]');
    let createdMap = new Map();
    for (let i = 0; i < jsonValues.length; i++) {
        createdMap.set(jsonValues[i].key, jsonValues[i].value);
    }
    console.log(createdMap);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.