Change key name in JavaScript object

前端 未结 4 601
眼角桃花
眼角桃花 2020-12-10 13:25

I am checking the attributes in a JavaScript object, replacing some of the keys by deleting the prefix \"element\" and saving the new values in another object.



        
4条回答
  •  一整个雨季
    2020-12-10 13:49

    We'll write a little function to fix the key the way you want.

    function fix_key(key) { return key.replace(/^element_/, ''); }
    

    Underscore

    _.object(
      _.map(_.keys(json), fix_key),
      _.values(json)
    )
    

    ES5/loop

    var keys = Object.keys(json);
    var result = {};
    
    for (i = 0; i < keys.length; i++) {
      var key = keys[i];
      result[fix_key(key)] = json[key];
    }
    
    return result;
    

    ES5/reduce

    Object.keys(json) . reduce(function(result, key) {
      result[fix_key(key)] = json[key];
      return result;
    }, {});
    

    ES6

    Object.assign(
      {},
      ...Object.keys(json) .
        map(key => ({[fix_key(key)]: json[key]}))
    )
    

    This makes an array of little objects each with one key-value pair, using the ES6 "computed property name" feature, then passes them to Object.assign using the ES6 "spread" operator, which merges them together.

提交回复
热议问题