Replace a single key in a json object

Hi All,

I want to replace just one keyname with another name. For example:

initial input :

{
Field1”: “bar”,
“Field2”: “bar”
}

desired output :

{
NEWNAME”: “bar”,
“Field2”: “bar”
}

I checked the docs and saw that we can use $.mapKeys to play with the keys.
https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1439367/Object+Functions+and+Properties#ObjectFunctionsandProperties-mapKeys

But I was not successful in changing the key. Whenever i tried, it was appending to all the keys in the object.
$.mapKeys((value, key) => “NEWNAME” + key)

When i used the below syntax, its giving only one key as output.
$.mapKeys((value, key) => “NEWNAME” + key)

Please help me to change just the name of a single key in the object.

Thanks in Advance.

Another approach would be to use a Mapper Snap with the “Pass through” option set. The first transformation would copy $Field1 to $NEWNAME and then the second would delete $Field1 (put $Field1 in the left side of the table and leave the right blank). I’m attaching a pipeline to demonstrate that:

RenameKey_2018_05_10.slp (4.4 KB)

Using mapKeys() might be more involved than necessary for a single key. In your example, you would need to use a conditional to change the result for the key you are interested in:

$.mapKeys((value, key) => key == "Field1" ? “NEWNAME” : key)

$.mapKeys((value, key) => key == ‘Field1’ ? ‘NEWNAME’ : key) has worked fine for me.

Also the approach I was using already is the 2 mapper approach you have suggested. One mapper for copying and second to delete. But I thought if we use this .mapKeys approach, we can do this with one mapper right. Thats why was thinking of the .mapKeys approach.

Anyway Thanks a lot for that!! :slight_smile: :slight_smile:

You should only need a single mapper in either approach. The delete transformations are done last. So, you can combine the copy and delete transformations into a single mapper.