admin 管理员组文章数量: 1086019
Lets say I have object:
{
cart: 4,
trolley: 10,
car: 2,
}
How can I turn it into:
{
shopping_cart: 4,
shopping_trolley: 10,
shopping_car: 2,
}
Lets say I have object:
{
cart: 4,
trolley: 10,
car: 2,
}
How can I turn it into:
{
shopping_cart: 4,
shopping_trolley: 10,
shopping_car: 2,
}
Share
Improve this question
asked Jul 5, 2022 at 18:17
AlyonaAlyona
1,8023 gold badges25 silver badges54 bronze badges
4 Answers
Reset to default 4You can get the keys of the object in an array using the Object.keys()
method. You can then use the Array.reduce()
method to iterate over each of the keys and create a new object with desired prefix.
let obj = {
cart: 4,
trolley: 10,
car: 2,
};
let pre = `shopping_`;
let nObj = Object.keys(obj).reduce((a, c) => (a[`${pre}${c}`] = obj[c], a), {});
console.log(nObj)
What have you tried so far?
var obj = {
cart: 4,
trolley: 10,
car: 2
}
for (var key in obj) {
obj["shopping_" + key] = obj[key]
delete obj[key]
}
console.log(obj)
const createPrefixObjectKeys => prefix => source => {
const prefixedSourceTuples = Object.entries(source).map(
([key, value]) => [
`${prefix}${key}`,
value
]
);
return Object.fromEntries(prefixedSourceTuples);
}
// use
const prefixObjectShopping = createPrefixObjectKeys('shopping_');
// where x is your object
const prefixed = prefixObjectShopping(x);
If you want to add keys even to nested objects in object. Use this (propably the easiest method)
function addKeyPrefixes(object, prefix){
return JSON.parse(
JSON.stringify(object).replace(/(?<=[{,]{1}\s*")(.+?)(?="\s*:)/gim, `${prefix}$1`)
)
}
let obj = {
'a' : {
'b': 'c'
},
'd': 4
}
console.log(addKeyPrefixes(obj, '_'))
// {
// '_a': {
// '_b': 'c'
// },
// '_d': 4
// }
本文标签: How to add prefix to object keys in javascriptStack Overflow
版权声明:本文标题:How to add prefix to object keys in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744097002a2533084.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论