cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Replace a single key in a json object

abjoe
New Contributor II

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#Ob...

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.

3 REPLIES 3

tstack
Former Employee

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)

abjoe
New Contributor II

$.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!! ๐Ÿ™‚ ๐Ÿ™‚

tstack
Former Employee

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.