Skip to content

Commit e701fe5

Browse files
committed
Add U.rename(map, oldKey, newKey).
1 parent 0fe4135 commit e701fe5

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/main/java/com/github/underscore/lodash/U.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1584,6 +1584,36 @@ private static Object makeObjectForRemove(Object value, final String key) {
15841584
return result;
15851585
}
15861586

1587+
@SuppressWarnings("unchecked")
1588+
public static Map<String, Object> rename(final Map<String, Object> map, final String oldKey, final String newKey) {
1589+
Map<String, Object> outMap = newLinkedHashMap();
1590+
for (Map.Entry<String, Object> entry : map.entrySet()) {
1591+
if (entry.getKey().equals(oldKey)) {
1592+
outMap.put(newKey, makeObjectForRename(entry.getValue(), oldKey, newKey));
1593+
} else {
1594+
outMap.put(entry.getKey(), makeObjectForRename(entry.getValue(), oldKey, newKey));
1595+
}
1596+
}
1597+
return outMap;
1598+
}
1599+
1600+
@SuppressWarnings("unchecked")
1601+
private static Object makeObjectForRename(Object value, final String oldKey, final String newKey) {
1602+
final Object result;
1603+
if (value instanceof List) {
1604+
List<Object> values = newArrayList();
1605+
for (Object item : (List) value) {
1606+
values.add(item instanceof Map ? rename((Map<String, Object>) item, oldKey, newKey) : item);
1607+
}
1608+
result = values;
1609+
} else if (value instanceof Map) {
1610+
result = rename((Map<String, Object>) value, oldKey, newKey);
1611+
} else {
1612+
result = value;
1613+
}
1614+
return result;
1615+
}
1616+
15871617
public static class FetchResponse {
15881618
private final boolean ok;
15891619
private final int status;

src/test/java/com/github/underscore/lodash/LodashTest.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,26 @@ public void removeMapKey() {
666666
U.remove(map2, "test");
667667
}
668668

669+
@Test
670+
public void renameMapKey() {
671+
Map<String, Object> map = U.newLinkedHashMap();
672+
map.put("-self-closing", "false");
673+
U.rename(map, "test", "test1");
674+
Map<String, Object> newMap = U.rename(map, "-self-closing", "-self-closing1");
675+
assertEquals("{\n"
676+
+ " \"-self-closing1\": \"false\"\n"
677+
+ "}",
678+
U.toJson(newMap));
679+
Map<String, Object> map2 = U.newLinkedHashMap();
680+
List<Object> list = U.newArrayList();
681+
list.add(U.newArrayList());
682+
list.add(U.newLinkedHashMap());
683+
map2.put("list", list);
684+
U.rename(map2, "test", "test1");
685+
map2.put("list", U.newLinkedHashMap());
686+
U.rename(map2, "test", "test1");
687+
}
688+
669689
@Test
670690
public void jsonToXml() {
671691
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<a></a>", U.jsonToXml("{\n \"a\": {\n }\n}"));

0 commit comments

Comments
 (0)