How to add key value to all items of a list of objects

Consider the following object:

my_obj_list = [

    {
        "fields": {
            "speech": {
                "stringValue": "example of speech"
            },
            "word": {
                "integerValue": "example of word"
            }
        }
    },
{
        "fields": {
            "speech": {
                "stringValue": "example of speech 2"
            },
            "word": {
                "integerValue": "example of word 2"
            }
        }
    }

]

I want to add the key {path:{stringValue:"this is the path"}} so the output is:

 my_obj_list_result = [
        {
            "fields": {
                "speech": {
                    "stringValue": "example of speech"
                },
                "word": {
                    "integerValue": "example of word"
                },
                "path": {
                    "integerValue": "path 1"
                }
            }
        },
    {
            "fields": {
                "speech": {
                    "stringValue": "example of speech 2"
                },
                "word": {
                    "integerValue": "example of word 2"
                },
                "path": {
                    "integerValue": "path 2"
                }
            }
        }
    ]

I tried adapting the answer from @Mazen_Al-Sakkaf to this post but had no success.

Hi Allan,

Try

my_obj_list.forEach((item, index,arr)=>arr[index].fields.path={"stringValue": "path " + index});

image

Hi Mazen. That works. Thank you! You already helped me a lot, but if you could only help me with one more question: let’s say I need to delete a key (e.g. “speech”), besides adding this new key called ‘path’. How to do it?

You are welcome! Alan,
You could use a delete statement.

delete my_obj_list[0].fields.speech;
1 Like