1

I have the below array which is being passed from other component.

var myArray = [
    {
        "Sequence": 1,
        "Value": 1,
        "sections": [
            {
                "Name": "Section 1",
                "Configurations": [
                    {
                        "Number": 1,
                        "Value": "Fruit"
                    },
                    {
                        "Number": 2,
                        "Value": "Vegetable"
                    }
                ],
                "Cost": {
                    "Currency": "INR"
                }
            }
        ]
    }
]

I want to loop through this array and add "isFruit" = true if "Value": "Fruit" and "isVegetable" = true if "Value": "Vegetable".

So the Expected Output is as below.

var myArray = [
    {
        "Sequence": 1,
        "Value": 1,
        "sections": [
            {
                "Name": "Section 1",
                "Configurations": [
                    {
                        "Number": 1,
                        "Value": "Fruit",
                        "isFruit": true
                    },
                    {
                        "Number": 2,
                        "Value": "Vegetable"
                        "isVegetable": true
                    }
                ],
                "Cost": {
                    "Currency": "INR"
                }
            }
        ]
    }
]

Seems the object is ready only and when I try as below it doesn't work. Tried with Spread Syntax but it goes only till 1 level and nested objects are still read only.

Someone please let me know how can I achieve the expected Output array.

1 Answer 1

1

As long as you have no circular or self references in your JSON, you can simply stringify and then parse the array to get a mutable version.

let mutableJSON = JSON.parse(JSON.stringify(jsonFromParent));

I tried a lot of other techniques to avoid this, as it seems pretty clumsy but it works well.

You can also try Object.assign but you do need to know if you have array or an object for this one.

const newArray = Object.assign([], jsonArrayFromParent);
3
  • Thank you. This helped. I was able to achieve the required output.
    – Sunil C N
    Apr 9, 2021 at 8:07
  • Glad to help - this can be tricky esp if you are moving from Aura to LWC Apr 9, 2021 at 8:08
  • Yes. That's the activity I am currently working on and was stuck at this part.
    – Sunil C N
    Apr 9, 2021 at 8:37

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.