如何转换json中的字段名
发布于 8 年前 作者 ldd911127 4602 次浏览 来自 问答

let test = [ {id: ‘testId’, text: ‘testText’}, {id: ‘testId1’, text: ‘testText1’}, {id: ‘testId2’, text: ‘testText2’} ]

let test_new = [ {id_new: ‘testId’, text_new: ‘testText’}, {id_new: ‘testId1’, text_new: ‘testText1’}, {id_new: ‘testId2’, text_new: ‘testText2’} ]

请教下如何快捷的将test字段转换成test_new 中的字段呢、现在用的比较笨的办法,用一个中间变量,forEach循环赋值,有没有是比较好的方法或者第三方插件支持呢

11 回复

循环然后赋值就是最快的方式了。没那么多魔法。。。

@alsotang 主要是这样写代码量会比较多,好多接口都要循环转换一下,没有其他方法只有循环赋值了

直接转换为string, 然后正则替换, 再转回来不就行了?

写成一个公用方法 然后需要的时候调用 不就可以了吗

var test2 = test.map(d => ({ id_new: d.id, text_new: d.text }))

@Qquanwei 这个不太推荐,如果有键值相同或者有重复片段,就挂了…

@DevinXian 确实,如果确定值里不会出现 “:” 字符就没太大问题

3L 肯定是在开玩笑

这只是一个思路, 如果你的数据能保证正则替换后的正确性,这种方式也是可以使用的。 要不然就只能暴力了!

回到顶部