Home > other >  How to add prefix to object keys in javascript?
How to add prefix to object keys in javascript?

Time:07-06

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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)

  • Related