Javascript 有没有办法使用underscore.js重命名js对象键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8747561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:19:20  来源:igfitidea点击:

Is there any way to rename js object keys using underscore.js

javascriptjqueryunderscore.js

提问by claya

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

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

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

needs to turn into

需要变成

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

where I have lookup obj available for mapping all the keys

我有查找 obj 可用于映射所有键的地方

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

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

underscore.js 或 jQuery 中是否有可用的函数来执行此功能?

thanks

谢谢

采纳答案by pimvdb

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/.

据我所知,这两个库中的任何一个都没有内置函数。不过,您可以相当容易地制作自己的:http: //jsfiddle.net/T9Lnr/1/

var b = {};

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

回答by Samir Aguiar

I know you didn't mention lodashand the answers already solve the problem, but someone else might take advantage of an alternative.

我知道您没有提到lodash并且答案已经解决了问题,但其他人可能会利用替代方案。

As @CookieMonster mentioned in the comments, you can do this with _.mapKeys:

正如评论中提到的@CookieMonster,您可以使用以下方法执行此操作_.mapKeys

_.mapKeys(a, function(value, key) {
    return serverKeyMap[key];
});

And the fiddle: http://jsfiddle.net/cwkwtgr3/

和小提琴:http: //jsfiddle.net/cwkwtgr3/

回答by dule

Similar to @pimvdb, you can also do it with a _.reduce:

与@pimvdb 类似,您也可以使用_.reduce

_.reduce(a, function(result, value, key) {
    key = map[key] || key;
    result[key] = value;
    return result;
}, {});

Fiddle: http://jsfiddle.net/T9Lnr/39/

小提琴:http: //jsfiddle.net/T9Lnr/39/

回答by user2387823

You could copy the values to the new properties with standard JavaScript, and remove the original properties with omit, as follows:

您可以使用标准 JavaScript 将值复制到新属性,并使用omit删除原始属性,如下所示:

a.id = a.name;
a.total = a.amount;
a.updated = a.reported;
a = _.omit(a, 'name', 'amount', 'reported');

回答by aemonge

It's been solved here https://stackoverflow.com/a/30940370/1360897

这里已经解决了https://stackoverflow.com/a/30940370/1360897

var keyMapping = {'PropertyA': 'propertyA', ..., 'PropertyF': 'propertyNEW'}

and also a mapping of old and new values, like this

以及新旧值的映射,像这样

var valueMapping = {'Y': true, 'F': false}

And then using _.map and _.transform, you can transform the object, like this

然后使用_.map和_.transform,就可以对对象进行变换,像这样

var result = _.map(allItems, function(currentObject) {
    return _.transform(currentObject, function(result, value, key) {
        if (key === 'PropertyF' || key === 'PropertyG') {
            value = valueMapping(value);
        }
        result[keyMapping[key]] = value;
    });
});

回答by Zin Kanzaki

// key_map: {old_name1: new_name1, ... }
function rename_keys(object, key_map, is_picked=false){
  keys = _.keys(key_map);
  new_keys = _.values(key_map);
  picked = _.pick(object, keys);
  renamed = _.object(new_keys, _.values(picked));
  if(is_picked) return renamed;

  return _.chain(object).omit(keys).extend(renamed).value();
}

This may be slower than above answers.

这可能比上述答案慢。

回答by Umesh Patil

Why don't you use this simple java script ? Value of any key:value pair should be string/number/Boolean.

你为什么不使用这个简单的java脚本?任何键值对的值应该是字符串/数字/布尔值。

<script type="text/javascript">    
    var serverKeyMap = {
        name : "id",
        amount : "total",
        reported : "updated"
    };

    var a = {
        name : "Foo",
        amount: 55,
        reported : false
    };

    var b={}; // b is object where you will get your output

    for(i in serverKeyMap) b[serverKeyMap[i]]=a[i];

    console.log(b); // It gives what you need.

</script>

回答by mr23

I have a transformation operator and would just like to apply it to all keys. I forked pimvdb's fiddle to produce a simple example. In this case it Capitalizes the key. And it dynamically builds the keymap, which I needed to assure works (thanks JSFiddle).

我有一个转换运算符,只想将它应用于所有键。我分叉了 pimvdb 的小提琴来产生一个简单的例子。在这种情况下,它会将密钥大写。它动态构建键盘映射,我需要它来确保工作(感谢 JSFiddle)。

Here is the changed code:

这是更改后的代码:

var keymap = {};
_.each(a, function(value, key) {
    var oldkey = key;
    key = capitalize(key);
    keymap[oldkey] = key;
});
_.each(a, function(value, key) {
    key = keymap[key] || key;
    b[key] = value;
});

Fiddle: http://jsfiddle.net/mr23/VdNjf/

小提琴:http: //jsfiddle.net/mr23/VdNjf/

回答by JaredMcAteer

No there is no function in either library that explicitly renames keys. Your method is also the fastest (see jsperf tests.) Your best bet, if possible, is to refactor either the client side or server side code so the objects are the same.

不,两个库中都没有显式重命名键的函数。您的方法也是最快的(请参阅jsperf 测试。)如果可能,您最好的选择是重构客户端或服务器端代码,以便对象相同。

回答by Brandon Howard

As user2387823 was saying aboveusing omitis a great option. For example you could write something like this

正如上面user2387823 所说使用omit是一个不错的选择。例如你可以写这样的东西

function updateObjKey(obj, currentKey, newKey) {
    var keyValue = obj[currentKey];
    obj = _.omit(obj, [currentKey]);
    obj[newKey] = keyValue;
    return obj;
  }