简体   繁体   中英

How to add prefix to object keys in javascript?

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,
}

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);

You 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM