Remove Characters from All Keys in an Object (Lodash OK)

前端 未结 5 1314
没有蜡笔的小新
没有蜡笔的小新 2021-01-27 19:46

I have a bothersome length of characters before all keys in this object. Since they are all the same, I would like to do a .map() or forEach() or some

5条回答
  •  鱼传尺愫
    2021-01-27 19:57

    Another approach that avoinds the need for Object.fromEntries(), would be to use Array.reduce() as shown:

    const input = {
      'remove.this.string.a': "apple",
      'remove.this.string.b': "banana",
      'remove.this.string.c': "carrot",
      'remove.this.string.d': "diakon"
    };
    
    const output = Object.entries(input).reduce((result, [key, value]) => {
      
      /* Pluck last letter of key string */
      const letter = key.slice(-1);
    
      /* Insert letter key/value into result object */
      return { ...result, [letter] : value };
      
    }, {});
    
    console.log(output);

提交回复
热议问题