有什么办法可以使用underscore.js重命名js对象键 [英] Is there any way to rename js object keys using underscore.js

查看:78
本文介绍了有什么办法可以使用underscore.js重命名js对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将js对象转换为另一个对象,以传递到例如键名不同的服务器帖子上

I need to convert a js object to another object for passing onto a server post where the names of the keys differ for example

var a = {
    name : "Foo",
    amount: 55,
    reported : false,
    ...
    <snip/>
    ...
    date : "10/01/2001"
    } 

需要变成

a = {
  id : "Foo",
  total : 55,
  updated: false,
  ...
  <snip/>
  ... 
  issued : "10/01/2001"
  }

我有可用于映射所有键的查找对象

where I have lookup obj available for mapping all the keys

var serverKeyMap = {
    name : "id",
    amount : "total",
    reported : "updated",
     ...
    date : "issue"
    }

underscore.js或jQuery中有可用的函数可以执行此功能吗?

Is there a function available in underscore.js or jQuery that I can use that does this functionality?

谢谢

推荐答案

据我所知,这两个库均未内置任何函数.不过,您可以相当轻松地制作自己的作品: http://jsfiddle.net/T9Lnr/1/.

As far as I know there is no function built into either of these two libraries. You can make your own fairly easily, though: http://jsfiddle.net/T9Lnr/1/.

var b = {};

_.each(a, function(value, key) {
    key = map[key] || key;
    b[key] = value;
});

这篇关于有什么办法可以使用underscore.js重命名js对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆