从对象的所有键中删除字符(Lodash OK) [英] Remove Characters from All Keys in an Object (Lodash OK)
本文介绍了从对象的所有键中删除字符(Lodash OK)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在此对象中的所有键之前,我都有一个令人讨厌的字符长度.由于它们都是相同的,所以我想做一个 .map()
或 forEach()
或一个带有 .slice()
的东西在其中删除前 n 个字符.如何对对象中的所有键进行此操作?
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 something with a .slice()
in it to remove the first n characters. How is this done to all keys in the object?
我应该说我们已经在项目中导入了Lodash,所以我可以使用它.
I should say that we are already importing Lodash in the project so I can use that.
所以我需要把这个转过来:
So I need to turn this:
{
'remove.this.string.a': "apple",
'remove.this.string.b': "banana",
'remove.this.string.c': "carrot",
'remove.this.string.d': "diakon"
}
并将其转换为:
{
"a": "apple",
"b": "banana",
"c": "carrot",
"d": "diakon"
}
推荐答案
使用object.entries获取键和值.循环更改密钥.
Use object.entries to get the keys and values. Loop over changing the key.
直接更改对象
var obj = {
'remove.this.string.a': "apple",
'remove.this.string.b': "banana",
'remove.this.string.c': "carrot",
'remove.this.string.d': "diakon"
}
// Object.entries(obj).forEach(function(arr) {
// var key = arr[0]
// var value = arr[1]
// delete obj[key]
// obj[key.split(".").pop()] = value
// })
Object.entries(obj).forEach(([key, value]) => {
delete obj[key]
obj[key.split(".").pop()] = value
})
console.log(obj)
或减少以创建新对象
var obj = {
'remove.this.string.a': "apple",
'remove.this.string.b': "banana",
'remove.this.string.c': "carrot",
'remove.this.string.d': "diakon"
}
// const updated = Object.entries(obj).forEach(function(obj, arr) {
// var key = arr[0]
// var value = arr[1]
// obj[key.split(".").pop()] = value
// return obj
// }, {})
const updated = Object.entries(obj).reduce((obj, [key, value]) => {
obj[key.split(".").pop()] = value
return obj
}, {})
console.log(updated)
这篇关于从对象的所有键中删除字符(Lodash OK)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文